Dev.to WebDev 🛠 Dev 👁 0

One regex change made path-to-regexp up to 41% faster

path-to-regexp turns routes such as /users/:id into regexes for Express. It has 312M npm downloads a week. One change to its escape step made stringify up to 41% faster. Before str.replace(/[.+*?^${}()[\]|

path-to-regexp turns routes such as /users/:id into regexes for Express. It has 312M npm downloads a week. One change to its escape step made stringify up to 41% faster.

Before

str.replace(/[.+*?^${}()[\]|/\\]/g, "\\$&");

"\\$&" is a replacement pattern. For each match, the engine reads it and inserts the matched text.

After

str.replace(/(?=[.+*?^${}()[\]|/\\])/g, "\\");

The lookahead matches the position before each special character. The replacement is a plain backslash. The output does not change.

Results

Benchmark (12 routes) Change
stringify, escaped characters -41%
match setup -28%
parse and pathToRegexp -23%
stringify, plain paths -15%

match and compile calls did not change. Old and new output matched on 1M random inputs.

PR: path-to-regexp #465

The rule

To insert fixed text, match the position with a lookahead and use a plain string, not $&.

Do you have a replace() with $& in a hot path? Tell me in the comments.

📰 Read the original article on Dev.to WebDev

Originally published by Dev.to WebDev. Aggregated on AIWithGhost for educational purposes — full credit and traffic to the original publisher.