Skip to content

perf: build toString output by concatenation - #367

Open
g4lb wants to merge 1 commit into
postcss:mainfrom
g4lb:perf-tostring-concat
Open

g4lb wants to merge 1 commit into
postcss:mainfrom
g4lb:perf-tostring-concat

Conversation

@g4lb

@g4lb g4lb commented Nov 18, 2026

Copy link
Copy Markdown

Node#toString and Container#_stringify build each result with an array and join(""). This change uses string concatenation instead. Container#_stringify still skips null and undefined child results, as join did. The output does not change.

Benchmark (built dist, Node.js 24.15.0) Before After Change
toString(), 617 parsed selectors, lossless 462 µs 370 µs -19.9%
toString(), 617 parsed selectors, lossy 450 µs 361 µs -19.8%
toString(), 300 small trees built with the node constructors 296 µs 247 µs -16.6%
processSync, 1000 empty and one-token selectors 861 µs 786 µs -8.8%
processSync with a transform that removes and adds nodes 3.96 ms 3.71 ms -6.4%
processSync, 617 selectors, lossless 2.74 ms 2.58 ms -5.8%
processSync, 617 selectors, lossy 2.65 ms 2.53 ms -4.5%

I measured no slowdown on 20 benchmarks. These include Bootstrap and Tailwind selectors, :is, :has and attribute selectors, escapes, invalid selectors, a long selector list, and walks. I used 12 interleaved rounds and a Mann-Whitney test (Apple M2 Max).

Testing:

  • npm test passes (1076 tests). node --test src/__tests__/*.mjs also passes on Node.js 20.20.2. On Node.js 16.20.2, attributes-deprecations.mjs fails with and without this change.
  • Parsed 1,000,000 random and mutated selectors with both versions: the AST, source positions, toString() output and errors were identical for every one.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant