lukeed / polka

A micro web server so fast, it'll make you dance! :dancers:
MIT License
5.4k stars 172 forks source link

perf(compression): use regex exec instead of match #210

Closed bluwy closed 2 months ago

bluwy commented 2 months ago

I was running eslint-plugin-regexp in polka and found we can refactor the str.match(re) to re.exec(str) for perf.

/Users/bjorn/Work/oss/vite/node_modules/.pnpm/@polka+compression@1.0.0-next.25/node_modules/@polka/compression/build.js
  30:32  error  Use the `RegExp#exec()` method instead  regexp/prefer-regexp-exec
  30:68  error  Use the `RegExp#exec()` method instead  regexp/prefer-regexp-exec

I made some tests and can confirm there's a sizable perf improvement with exec. (perf.link test)

kurtextrem commented 2 months ago

might make sense to hoist the regexps too?

bluwy commented 2 months ago

The perf improvement from hoisting regex varies quite a bit in my experience and often doesn't yield noticable returns. I think engines are able to optimize them well enough these days. Maybe those with g flags could still be useful to hoist as they're more stateful.

lukeed commented 2 months ago

released as @polka/compression@1.0.0-next.26, ty @bluwy

kurtextrem commented 2 months ago

@bluwy Last time we benched it for valibot, it was ~2ms faster to hoist (even non global regexps)

bluwy commented 2 months ago

Yeah it'll depend but it's often a very small amount that I've come to prefer not bugging libraries to hoist them unless really needed 😅

lukeed commented 2 months ago

It generally has a significant impact in repeat synchronous usage (eg loops), so seeing it in valibot makes sense. In an async-like callback (like here) it won’t matter much, especially with simple patterns