Skip to content

perf(escape): scan short strings with a loop instead of the regex - #86

Merged
BridgeAR merged 1 commit into
BridgeAR:mainfrom
g4lb:perf-escape-short-strings
Nov 19, 2026
Merged

BridgeAR merged 1 commit into
BridgeAR:mainfrom
g4lb:perf-escape-short-strings

Conversation

@g4lb

@g4lb g4lb commented Nov 18, 2026

Copy link
Copy Markdown
Contributor

strEscape tests each string with a regular expression. For strings of fewer than 10 characters, a charCodeAt loop finds the same characters faster. Longer strings use the current code.

Benchmark (Node.js 24.15.0) Before After Change
array of 300 strings of 3 characters 9.97 µs 7.40 µs -25.8%
array of 300 strings of 9 characters 12.5 µs 10.3 µs -17.1%
array of 300 short strings that need escaping 23.6 µs 20.5 µs -13.3%
test.json from compare.js, eight copies 154 µs 139 µs -9.4%
the same with deterministic: true 180 µs 167 µs -7.7%

I measured no slowdown on 33 benchmarks, including strings of 10 to 25 characters. I also tried a limit of 24 and of 16. Then, strings just below the limit were 35% and 7.5% slower, so I used 10. I used 12 interleaved rounds and a Mann-Whitney test (Apple M2 Max).

npm test passes on Node.js 24.15.0, and tap passes on Node.js 18.20.8. Old and new output matched on 1,000,000 random values with random options.

@BridgeAR BridgeAR left a comment

Copy link
Copy Markdown
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

LGTM, thank you

@BridgeAR
BridgeAR merged commit 08f0e68 into BridgeAR:main Nov 19, 2026
5 checks passed
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.

2 participants