Skip to content

perf: use indexed capture groups instead of named ones in parse()#283

Open
ordinary9843 wants to merge 1 commit intovercel:mainfrom
ordinary9843:perf/use-indexed-capture-groups
Open

perf: use indexed capture groups instead of named ones in parse()#283
ordinary9843 wants to merge 1 commit intovercel:mainfrom
ordinary9843:perf/use-indexed-capture-groups

Conversation

@ordinary9843
Copy link

Noticed that v4 is quite a bit slower than v2 (#273), so I dug into why.

The regex in parse() was changed to use named capture groups ((?<value>...), (?<unit>...)) when the TypeScript rewrite happened. Named capture groups are slower in V8 — the engine needs to allocate an extra groups object and do property lookups instead of just reading an array index. This is a known V8 thing and it adds up fast in hot paths.

The fix is just switching back to indexed groups and reading match[1] / match[2]. No behavior change, just faster.

Numbers on my machine (Node 20, 500k iterations over 8 inputs):

time
before (named CG) ~475ms
after (indexed CG) ~286ms

That's roughly 66% faster for parse(), which lines up with what was reported in #273.

All 167 existing tests pass.

Named capture groups are noticeably slower in V8 because the engine has
to allocate a groups object and do property lookups. Switching back to
indexed groups (match[1], match[2]) is a simple change that gets parse()
back closer to v2 speed.

Fixes vercel#273
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