From 342d4624732518501b51a6a8b2f9ac2af783738a Mon Sep 17 00:00:00 2001 From: Jerry Chen Date: Fri, 20 Mar 2026 10:24:15 +0800 Subject: [PATCH] perf: replace named capture groups with indexed ones in parse() 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 #273 --- src/index.ts | 12 ++++-------- 1 file changed, 4 insertions(+), 8 deletions(-) diff --git a/src/index.ts b/src/index.ts index d50e3c7..da687c8 100644 --- a/src/index.ts +++ b/src/index.ts @@ -75,20 +75,16 @@ export function parse(str: string): number { ); } const match = - /^(?-?\d*\.?\d+) *(?milliseconds?|msecs?|ms|seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|months?|mo|years?|yrs?|y)?$/i.exec( + /^(-?\d*\.?\d+) *(milliseconds?|msecs?|ms|seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|months?|mo|years?|yrs?|y)?$/i.exec( str, ); - if (!match?.groups) { + if (!match) { return NaN; } - // Named capture groups need to be manually typed today. - // https://github.com/microsoft/TypeScript/issues/32098 - const { value, unit = 'ms' } = match.groups as { - value: string; - unit: string | undefined; - }; + const value = match[1]; + const unit = match[2] ?? 'ms'; const n = parseFloat(value);