From cf3a5073ece9eb313bb4832b3f78aa1bfeca09c6 Mon Sep 17 00:00:00 2001 From: arturovt Date: Sat, 25 Jan 2025 00:56:56 +0200 Subject: [PATCH] refactor(core): improve `stringify` (#59745) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit In this commit, we improve branching in the `stringify` function, which is widely used by the framework, and add additional comments for clarification. Benchmark results of the old and new implementations (using `slice` makes it slightly faster) are as follows: ``` stringify (old version) x 117,945,419 ops/sec ±5.25% (55 runs sampled) stringify (new version) x 136,692,820 ops/sec ±4.82% (56 runs sampled) ``` PR Close #59745 --- packages/core/src/util/stringify.ts | 23 ++++++++++------------- 1 file changed, 10 insertions(+), 13 deletions(-) diff --git a/packages/core/src/util/stringify.ts b/packages/core/src/util/stringify.ts index 916ddeaeb49..64cca9475a0 100644 --- a/packages/core/src/util/stringify.ts +++ b/packages/core/src/util/stringify.ts @@ -12,29 +12,26 @@ export function stringify(token: any): string { } if (Array.isArray(token)) { - return '[' + token.map(stringify).join(', ') + ']'; + return `[${token.map(stringify).join(', ')}]`; } if (token == null) { return '' + token; } - if (token.overriddenName) { - return `${token.overriddenName}`; + const name = token.overriddenName || token.name; + if (name) { + return `${name}`; } - if (token.name) { - return `${token.name}`; + const result = token.toString(); + + if (result == null) { + return '' + result; } - const res = token.toString(); - - if (res == null) { - return '' + res; - } - - const newLineIndex = res.indexOf('\n'); - return newLineIndex === -1 ? res : res.substring(0, newLineIndex); + const newLineIndex = result.indexOf('\n'); + return newLineIndex >= 0 ? result.slice(0, newLineIndex) : result; } /**