Writing patterns that run fast
Anchor it, start with a literal, drop the leading .*, avoid nested quantifiers, and measure. Real timings, including three tricks that made no difference.
Catastrophic backtracking and ReDoSGreedy and lazy quantifiersAnchors and line boundariesNon-capturing groupsAlternation
Writing patterns that run fast
The player loads from youtube-nocookie.com when you press play. Nothing reaches YouTube before that.
Not started
What you'll learn
- Anchor patterns that must match a whole string. /^\d+$/ ran in 0.02 ms where unanchored /\d+$/ took 450 ms on the same 40,000 digits and a trailing x.
- Start with something specific. /ERROR code=\d+/ took 0.19 ms on a 2.7 MB log and /\w+ code=\d+/ took 11.6 ms, about 60 times longer.
- Do not lead with .*. /.*foo/ on 40,000 characters without foo took 688 ms and /foo/ took no measurable time. Leading .* is already implied by an unanchored search.
- Prefer a negated class for delimited text, but know why: on well-formed text V8 ran [^"]* and .*? equally fast. The class matters for correctness across lines and for engines that backtrack more.
- Measure on realistic input, warm, several times. Hoisting a regex out of a loop was 3 times faster, while capture groups, non-capturing groups and a trie made little or no difference.
Speed comes from doing less
You’ve seen that an engine can spend its time in two ways: trying a match at too many places, and backing off too many times at each. Nearly every speed rule is one of those two, restated. Rather than recite a list, I ran each rule on Node 26 and kept the ones that earned their place. Every number is a median of seven runs after a warm-up run.
Anchor what must match whole
/\d+$/ unanchored, 10,000 digits then x 27 ms
20,000 digits 113 ms
40,000 digits 450 ms
/^\d+$/ anchored, 40,000 digits 0.02 ms
Twice the input, four times the time: quadratic. Unanchored, the engine tries every start position in the digit run and each attempt scans to the end before the x kills it. With ^, one attempt fails and it stops. If a pattern means “the whole string”, say so with ^ and $. Lesson 37 had the same effect at larger scale, where anchoring took 9.4 s down to 7 ms.
Start with something specific
I generated a 2.74 MB, 60,000-line log with 120 lines containing ERROR code=N. All four patterns find the same 120:
/ERROR code=\d+/g 0.19 ms
/(?:INFO|ERROR) code=\d+/g 0.34 ms
/[A-Z]+ code=\d+/g 1.66 ms
/\w+ code=\d+/g 11.55 ms
A pattern that begins with a literal lets the engine look for that text and only begin a real match where it occurs. One that begins with \w+ has to try at almost every character, and then grab a run of letters each time. I measured the difference, about 60 times between the first and last line. I did not look inside V8 to see why, so treat “scan for the literal” as the likely explanation.
Do not lead with .*
/.*foo/ no foo, 10,000 chars 43 ms
20,000 chars 171 ms
40,000 chars 688 ms
/foo/ no foo, 40,000 chars 0.00 ms
An unanchored search already allows anything before the match, so a leading .* adds nothing to meaning and adds a quadratic cost: from every start it runs to the end of the line and backs off looking for foo. If you want what comes after foo, capture that part instead.
Avoid ambiguity inside repeats
Nested quantifiers and overlapping alternatives, such as (a+)+ and (a|a)+, are the exponential cases from the last two lessons. \s+$ and .*.*= are the polynomial ones. Rewrite them so only one way to match exists: a+ for (a+)+.
Measure, because intuition lies
Several things I expected to matter did not.
Negated class versus lazy dot. On 1.42 MB of text with 80,000 quoted strings, /"[^"]*"/g took 1.35 ms and /".*?"/g took 1.37 ms in V8. Equal. In lesson 36’s PCRE2 trace the class took fewer steps, so it is cheaper in some engines, but V8 hid it here. The better reason to prefer the class is meaning: on say "hi newline more text "ok" end, "[^"]*" matched across the line break ("hi\nmore text "), ".*?" matched "ok", and "[^"\n]*" matched "ok". The class needs \n excluded in that case.
Capture groups. On a 100,000-line CSV-like text, /(\d+),(\w+),(\d+)/g took 1.62 ms, the non-capturing version 1.24 ms and the group-free version 1.48 ms. That is noise. Use (?:...) so group numbers stay stable, not to go faster.
Tries for alternations. For 2,000 words in an alternation against 238 KB of text, V8 ran the plain alternation in 0.10 ms and a trie-structured regex in 0.15 ms: no help. In Python 3.9 the alternation took 2.82 ms and the trie 1.90 ms, and a split-plus-set lookup was fastest at 1.28 ms. The trie idea from the deeper link buys something at most, and sometimes a plain Set beats any regex.
Hoisting. The one trick that was clear: running new RegExp("^item\\d+$").test(s) over 200,000 strings took 9.1 ms, and a regex literal created once outside the loop took 2.9 ms. Build once.
Measure properly
A first call is slower. In lesson 37 a brand-new regex took 3,159 ms on its first call and about 280 ms after, on the same input. So run once to warm up, then several times, and look at the median. Use input like the real thing: my log test used 2.7 MB with rare matches, and a toy string tells you little. Microbenchmarks are also single-machine: these numbers will differ on yours, but the ratios between rules should hold roughly.
About the video
“Faster, Faster! Improving regex performance with atomic grouping, possessive quantifiers and more!” is a PyCon AU 2023 talk, published 23 August 2023, 29 minutes 54 seconds. The description says it explains why regex can be slow on large data and what to do, and that many techniques apply beyond Python. The chapters read “Basic optimization rules”, “Flags and quantifiers”, “Grouping and dot usage”, “Backtracking mechanics”, “Atomic and possessive tools” and “Summary of best practices”. I clipped it to everything before the Q&A. I couldn’t read a transcript, so I can’t say which of my rules it states. This is the same video as the previous lesson’s, because it is the best fit I found for both. A correction in the description is about the Python regex cache size. English per its title and description.
What I did not run
RE2 and Go performance on these patterns, Python timings beyond the alternation test, regex JIT internals, and any engine’s literal-prefix optimisation directly. I did not test the i flag’s cost or Unicode flags’ cost. The comparisons are single-machine microbenchmarks.
Next
With the engine understood, the second half of the roadmap puts patterns to work. First up is a task everyone tries, validating emails, URLs and addresses.
Check yourself
Why is /\d+$/ far slower than /^\d+$/ on a long string of digits ending in x?
Unanchored, the engine retries at every start position, and each attempt scans the remaining digits before failing at the x. That is quadratic. Anchored, it tries once, fails at the x, and stops.
Why does starting a pattern with a literal make a search faster?
The engine can scan for that literal text directly and only start a full match where it appears. A pattern that begins with \w+ or a class has to attempt a match at nearly every position.
You write /.*foo/ to check whether a string contains foo. What is wrong with it?
The leading .* is redundant, since an unanchored search already allows anything before the match, and it is expensive: it scans to the end of the line from each start and backs off. Just use /foo/.
You replace capturing groups with (?:...) hoping for a speed-up. What did my measurement show?
Nothing meaningful. Capturing, non-capturing and group-free versions took 1.6, 1.2 and 1.5 ms, which is within the noise. Use (?:...) for clarity and stable group numbers, not for speed.
Go deeper
Notes
Notes are saved to your account.
Everything else on this page works without one — progress and bookmarks keep themselves in this browser and come with you when you sign in. Notes are the one thing worth not trusting to a browser you might clear.
Your notes could not be loaded.