refactor(core): improve stringify (#59745)

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
This commit is contained in:
arturovt 2025-01-25 00:56:56 +02:00 committed by Jessica Janiuk
parent 967488247e
commit cf3a5073ec

View file

@ -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;
}
/**