Repository navigation
Conversation
|
Build successful! You can test your changes in the REPL here: https://babeljs.io/repl/build/63562 |
|
commit: |
| // Force V8 to flatten the pending chunk in place. Note that neither | ||
| // `+str` (the "flatstr" trick) nor `str.charCodeAt(0)` flatten a cons | ||
| // string: they walk it. Searching does. | ||
| this._str.includes("\0"); |
There was a problem hiding this comment.
Is there any way we can write a test to make sure that _flattenChunk flattens? Maybe using some V8 intrinsics?
There was a problem hiding this comment.
I will work on that. When rebasing onto the upstream, the generator roundtrip test (#18546) just catches a bug introduced in the generatorInfoMaps refactor. I will fix that as well.
There was a problem hiding this comment.
Interesting, it turns out that the flatten trick still work. I have added a test using v8 intrinsic %StringIsFlat. The test is failing on _str.includes and passing on the +str trick.
c386751 to
124e1e4
Compare
| const parentId = generatorInfosMap.get(parent.type)![1]; | ||
| const needsParens = generatorInfosMap.get(child.type)?.[2]; | ||
| const parentId = generatorInfos[parent.type]![1]; | ||
| const needsParens = generatorInfos[child.type]?.[2]; |
There was a problem hiding this comment.
This part was previously not included in this PR. It was introduced in the #18546 and now we have to update the usage here as well.
`SourceMap#mark` built two objects per call and went through gen-mapping's `maybeAddMapping`, which then had to look up the previous segment to detect duplicates. Call `addSegment` directly, and skip the segments that gen-mapping would have skipped anyway (identical to the previous segment on the same generated line, or a sourceless segment that starts a line or follows another sourceless one) using the last-segment data we already track. Also cache the normalization of `loc.filename`, which was running a regex replace for every single mark. Source map generation is ~9% faster on jquery and on the TypeScript parser source; the generated mappings are byte-for-byte identical. Assisted-by: Claude Fable 5.1
`Printer#print` allocated a bound function for every node, just to pass it to `exactSource`, which forwarded it to `Buffer#exactSource`. Inline the source position bookkeeping into `print` and call the node generator directly. Also flatten the `_append` -> `_maybeIndent` -> `_shouldIndent` -> `endsWith` -> `getLastChar` call chain, which ran for every token, and inline the leading comments check. Assisted-by: Claude Fable 5.1
`print` looked up the generator of every node in a `Map`. A dictionary-mode object is ~5ns faster per lookup in V8, because the keyed load is handled by the inline cache rather than by a builtin call, and this lookup was ~4% of the whole generator time. Assisted-by: Claude Fable 5.1
- Load `node.property` once in `MemberExpression` and check its type directly, instead of calling `isMemberExpression` and `isLiteral` for every identifier property. - Don't stringify numeric literals when their raw value is printed. - Hoist `isNonDecimalLiteral` out of `Printer#number`, which created a closure on every call. - Read the last character once in `token`/`tokenChar`/`word`, and drop `Buffer#getNewlineCount`. - Only load `node.loc` in `print` when source maps, `retainLines` or `preserveFormat` need it. - Only run the indentation regexes on multi-line block comments, and cache the regexes by indentation width. These are individually within measurement noise. Assisted-by: Claude Fable 5.1
Use the `%StringIsFlat` V8 intrinsic (Node.js 24+) to check that each chunk moved out of `Buffer#_str` was flattened by the `+str` trick, both in unoptimized code and when `_append` is inlined into TurboFan-optimized code, where an unused `str.includes()` would be eliminated as dead code. Assisted-by: Claude Opus 5.5
124e1e4 to
309ea18
Compare
| if ( | ||
| !noIndent && | ||
| buf._last === charCodes.lineFeed && | ||
| buf._queuedChar === 0 && | ||
| this._indent > 0 | ||
| ) { | ||
| buf._appendChar(-1, this._indent, false); | ||
| } |
There was a problem hiding this comment.
Did we inline it manually? How much performance improvement will this bring?
There was a problem hiding this comment.
Yes, we inlined a chain of four functions here: _maybeIndent, _shouldIndent, endsWith, getLastChar. The condition is equivalent between these two variants.
Here is a comparison between the PR version (hand-inlined) with the original version. I draft this with the help of Claude:
TurboFan machine code (arm64)
Both versions compile to one map check on this, and then loads with no calls left. Neither needs a map check on _buf, because V8 tracks that field's type. The common case here is that the last character is not a newline:
The original version check _queuedChar first, then _last (2 loads, 3 branches, 1 compare). The PR version check _last and exit early if it is not a newline (1 load, 1 compare). So the hand version saves one load a few instructions per token: This is at most 1% on jquery test cases, within noise-level though.
Note that there is one hidden difference: The original _append and _appendChar are 27 and 30 bytes of bytecode, within V8's 30-byte small-function limit, so TurboFan always inlines them. The flattened versions are 78 and 81 bytes and do count against this small-function limit. So in the jquery run, word and token stopped inlining _append and called it instead. The original version kept a call there too (to Buffer#append), so it's still one call per token either way; but the call moves due to different bytecode size.
Here is result of reverting this change, one process per variant, 6 alternating rounds, median ms of generate() calls
| input | mode | _maybeIndent |
inlined | diff |
|---|---|---|---|---|
| jquery-3.6.js | plain | 5.17 | 5.09 | +1.6% |
| jquery-3.6.js | with source map | 9.16 | 9.32 | -1.7% |
| ts-parser.ts | plain | 7.18 | 6.77 | +6.0% |
| ts-parser.ts | with source map | 12.37 | 12.26 | +0.9% |
| typescript-5.6.2.js (9 MB) | plain | 161.72 | 158.22 | +2.2% |
| typescript-5.6.2.js (9 MB) | with source map | 279.39 | 277.11 | +0.8% |
Lower tiers
Without TurboFan, the original version is still 4-5 real calls per token. This matters for short-lived builds since they never get a chance to be optimized by TurboFan. Here is median of 15 generate() calls, unit is ms.
| input | tiers | original _maybeIndent |
inlined version (This PR) |
|---|---|---|---|
| jquery-3.6.js | --no-maglev --no-turbofan (Sparkplug) |
34.2 | 30.9 (-10%) |
| ts-parser.ts | --no-maglev --no-turbofan (Sparkplug) |
43.9 | 39.0 (-11%) |
| jquery-3.6.js | --no-turbofan (Maglev) |
7.4 | 7.2 (-3%) |
| ts-parser.ts | --no-turbofan (Maglev) |
9.4 | 9.4 (~0%) |
| // A plain object is faster than a Map for string-keyed lookups, since | ||
| // V8 can inline the dictionary lookup in the keyed load IC. |
There was a problem hiding this comment.
Hmm, this is unexpected. Maybe my previous tests didn't reflect the true situation. :)
There was a problem hiding this comment.
Yes I have also been curious about the performance of Map.get() vs Keyedload-IC. Today I prompted Claude to deep dive on these two.
Here is its report, I have edited only a few words:
It depends on the key pattern, so your earlier tests may well have been right for what they measured.
TurboFan compiles both to one builtin call in print: generatorInfos[type] becomes KeyedLoadICTrampoline_Megamorphic, and generatorInfosMap.get(type) becomes FindOrderedHashMapEntry plus an inline load of the value. I single-stepped one lookup of every node type in jquery under lldb (Node 26.10, type strings straight from @babel/parser, so internalized):
On an arm64 environment:
- The keyed load IC runs about 100 instructions (22 loads): load the feedback vector, check the key's instance type and hash, check the receiver is a dictionary-mode object, probe the
NameDictionary, check the property details, return. ANameDictionaryis at most half full, so with 2 of the 3 hash seeds I tried, 92% of lookups hit on the first probe, and the path is almost always the same. FindOrderedHashMapEntryis shorter: about 60–70 instructions (9 loads) plus ~12 inline. Keys are compared by pointer, with noStringEqual. But anOrderedHashMaphas about two entries per bucket, so it walks a chain whose length depends on the key: 1 to 7 compares across the jquery types, with a different mix for each hash seed.
So Map#get does less work but has a data-dependent loop exit, and on a real node sequence that branch mispredicts. Timing the lookup alone (ns per lookup, median of 3 processes, --hash-seed pinned because V8 randomizes it per process):
| hash seed | jquery node types: object | jquery node types: Map |
always "Identifier": object |
always "Identifier": Map |
|---|---|---|---|---|
| 1 | 7.4 | 14.9 | 8.0 | 6.4 |
| 2 | 7.8 | 12.1 | 7.8 | 5.2 |
| 3 | 11.9 | 13.1 | 8.2 | 4.4 |
With one repeated key, Map#get wins by 2–4 ns. With the real mix of node types, the object wins by 1–7 ns. Seed 3 is the one where only 45% of the dictionary lookups hit on the first probe. If your earlier test used a single key or a small repeating pattern, I think that explains the difference.
End to end it is a small effect. At ~4 ns per lookup and ~38k printed nodes, jquery saves about 0.15 ms of 5 ms, which matches what I measured with only this commit reverted (Node 26.10, node:bench, one process per variant, 6 alternating rounds, ms per generate() call, median):
| input | mode | Map |
object | diff |
|---|---|---|---|---|
| jquery-3.6.js | plain | 5.14 | 4.96 | +3.6% |
| jquery-3.6.js | map | 9.18 | 8.86 | +3.6% |
| ts-parser.ts | plain | 6.67 | 6.53 | +2.1% |
| ts-parser.ts | map | 12.04 | 12.11 | -0.6% |
| typescript-5.6.2.js (9 MB) | plain | 154.18 | 155.25 | -0.7% |
| typescript-5.6.2.js (9 MB) | map | 267.23 | 265.64 | +0.6% |
(plain is generate(ast), map adds sourceMaps: true; diff > 0 means the object is faster.) The other inputs are within noise, partly because each process gets a random hash seed.
ASTs that come from JSON.parse or structuredClone don't change the picture: the first lookup internalizes the type string in place (it becomes a ThinString), for both the object and the Map.
@babel/generatorperformance based on the profileIn this PR we improve the
@babel/generatorperformance based on the CPU profile ofjquery-3.6.js.txt,ts-parser.ts.txtandtypescript-5.6.2.js.txt. The following changes are implemented:addSegmentdirectly and skip redundant segments on the Babel side, avoiding two allocations per mark and themaybeAddMappinglookup. Also cacheloc.filenamenormalization.print: remove the bound function allocated per node and flatten the_appendindentation call chain.Map.Generator throughput compared with
main, using isolated per-processnode:benchruns (noise floor about ±2%):jquery-3.6.js.txtts-parser.ts.txttypescript-5.6.2.js.txt(9MB)Note: The
ts-parser.ts.txtplain result is noisy: individual rounds range from -2% to +14%.After this PR, the impact of the number of hidden classes behind each AST node is more significant: Further generator performance improvement is possible if we change the AST and avoid conditional property assignment, such as
{leading,inner,trailing}Commentsandloc. Local experiment shows another 10% bump if the parser can avoid conditional AST properties.Updated 2026-11-19:
The output buffer is unchanged. An earlier revision of this PR replaced the
+str"flatstr" trick withstr.includes("\0")in 64KB chunks, assuming that+strdoesn't flatten cons strings. That assumption was wrong:+strflattens the string in place in every V8 tier, while an unusedstr.includes()is removed as dead code once TurboFan inlines it. Main's buffer was as fast or faster, so that change was dropped.We added a test, as suggested by @nicolo-ribaudo in the review: It uses the
%StringIsFlatV8 intrinsic (Node.js 24+ only) to check that each chunk is flat when it is moved out ofBuffer#_str, both in unoptimized code and when_appendis inlined into TurboFan-optimized code. The test fails if+stris replaced withstr.includes("\0").