SIGN IN SIGN UP

perf(packages/codegen): faster string flattening (#26108)

As noted in #26106, user code will end up flattening the output of `printSync`, and it's slow.

Since that cost is inevitable, we might as well make flattening the string part of `printSync`s responsibility, and make sure the cost is as low as possible.

V8 has 2 different methods of flattening a string. One of them is optimized for for exactly the shape of string that codegen produces - a rope which has been generated by repeated `output += segment` appends. The other (which would be more likely to be triggered by user code) is about 2x slower for ropes of this shape.

So here we use the faster one, which we trigger with `output.indexOf(" ")`. Except in the weirdest of weird cases, a space will appear early in the output, so `indexOf` won't have to search far. Even if it _does_ have to search the whole string, that's still faster than the slower flatten path.

The change to benchmarks made in #26106 flattened the output string with `output.charCodeAt(0)` which is the slower flatten path. In comparison, using the faster flatten, has a large effect (smaller is faster):

| Fixture | Bytes | Change |
|:---| ---:| ---:|
| `tiny.js` | 26 | \-23.5% |
| `RadixUIAdoptionSection.jsx` | 2,424 | \-41.8% |
| `react.development.js` | 50,496 | \-24.2% |
| `binder.ts` | 126,212 | \-23.4% |
| `lodash.js` | 182,262 | \-17.6% |
| `App.tsx` | 298,130 | \-14.9% |
| `kitchen-sink.tsx` | 662,560 | \-15.6% |
| `antd.js` | 5,100,647 | \-16.8% |
O
overlookmotel committed
487427aa201efa526218fa5a0200d475dee2f069
Parent: 7785583