The Regex Monster Revisited: a Lazy DFA for Go's regexp
Last February I wrote about taming a regex
monster:
an alternation of a hundred 8-letter literals from a Gophers Slack
discussion. The DFA of modernc.org/regexp matched it about 28x faster than
the standard library. The catches were a compile tax of about 200x, and a
hand-written proof-of-concept VM around NewMatchDFA, because the DFA choked
on the .*s around the literals and had to be fed the bare alternation. Rob Pike pointed out that a list of literals is a job for
Aho-Corasick, not for regular expressions, and he was right.
Since then the DFA has been rewritten, and the tax is gone. Since v1.10.0 the
package runs a lazy DFA, in the style of RE2’s and of Rust’s
regex-automata, behind the ordinary Regexp API. v1.11.2 is the current
release. This post revisits the monster, sketches how the DFA works, and
lists what I learned on the way. Some of the lessons were embarrassing.
The monster, revisited
Same pattern, same inputs, plain regexp.MustCompile and MatchString. One
CPU, median of 5:
Feb 2026, VM over NewMatchDFA |
v1.11.2, plain Regexp |
stdlib | |
|---|---|---|---|
| Compile | 15.7 ms | 101 µs | 101 µs |
| No match (1387 bytes) | 74.9 µs | 4.65 µs | 2.14 ms |
| Match (1388 bytes) | 36.7 µs | 2.44 µs | 1.04 ms |
The February numbers come from that post. The stdlib numbers then and now agree within the noise.
So Compile now costs what the stdlib’s does, and matching is 420 to 460
times faster than the stdlib, against the 28x of February. The follow-up,
with |\pL\p{Nd}*Z?4-? added so that no fixed set of strings can stand in
for it (4.8x in February), measures the same: 2.37 µs against the stdlib’s
1.09 ms.
For literals, the lazy DFA ends up building something very like an
Aho-Corasick automaton, and only the states the input needs.
The form from the Slack discussion, ^(?s:.*zQPbMkNO.*|.*NNSPdvMi.*|...)$,
is another story, and it gets its own lesson below.
How it works, in short
- Nothing is built at
Compile. The DFA’s states are made during a search, from the samesyntax.Progthat the stdlib’s engines run, for the input the search meets. That’s why the compile tax is gone. - A state is an ordered list of program counters plus a few flags, for
example “after a word character”, so that
\b,^and$work. The order is thread priority. When a thread matches, the threads of lower priority are cut, so the result is exactly the stdlib’s leftmost-first match, not just a match. Matchstops at the first match.Findscans forward to the end of the leftmost-first match, then runs the DFA of the reversed regexp backward to find its start. A regexp whose every match ends at the end of the text is searched backward from the end only.- Submatches still come from the stdlib’s engines, started at the match that the DFA found. When the regexp anchored at both ends is one-pass, which many regexps that aren’t one-pass themselves are, the groups take a single pass.
- Between matches the search jumps: to the literal prefix, to the next of at most three possible first bytes, or to just before a literal that every match must contain.
- Each goroutine gets its own cache of states, with a 2 MB budget. A search that keeps filling its cache gives up (RE2’s rule), and the stdlib’s NFA takes over, so time stays linear.
- Whatever the DFA doesn’t handle falls back to the stdlib’s engines:
io.RuneReaderinputs, leftmost-longest bounds, huge programs, and Go before 1.24.
It is a drop-in replacement of regexp as of Go 1.27.3. Go’s own regexp
tests pass, RE2’s exhaustive tests included. A fuzzer compares every result
with the stdlib, and 22 builders, from linux/s390x to windows/arm64, pass.
What I learned
Build only what the input needs. The old DFA was determinized at
Compile with a general-purpose automaton library. That was the 200x
compile tax, paid even when the attempt failed. It also forced the package
to refuse patterns whose priorities it couldn’t track exactly, \b and most
alternations among them. The lazy DFA pays per state actually visited,
handles all of them, and Compile went back to within a few percent of the
stdlib.
Use the standard library as the oracle. FuzzStdlib feeds random
patterns and inputs to both packages and compares everything: match, bounds,
groups, Split, ReplaceAll, errors. Run against the old DFA in October, it
found wrong results, all of them present in v1.7.10, the version of the
February post. In November I found the old DFA restarting after every failed attempt, so [a-z]+@[a-z]+\.com on 16 KB
of as took 1.4 s against the stdlib’s 0.5 ms. That was in a package whose
documentation promises linear time. The rewrite makes linear time a property
of the design rather than of a step budget.
Fuzzers don’t reach your thresholds. v1.11.0 had a false match.
[\x{FFFD}α]ab matched a run of emoji followed by “ab”: MatchString
returned true while FindStringIndex returned nil. The inner-literal skip
jumped to a fixed distance before the literal, which could land in the
middle of a multibyte rune. Decoding from there reads invalid UTF-8, which is
U+FFFD, which the class accepts. The skip only runs with 32 or more bytes
left, and the fuzzer never combined that with the right bytes. An outside
review found it. The fix moves the skip target to the next rune start, and
the fuzzer now also runs every input with the thresholds at zero.
Bound the first use too. The same review found that a regexp of 9000
\pLs took over a second and 374 MiB on its first match, while the classes
were built. Linear time per search says nothing about the setup. The classes
are now built from the distinct character sets only, with hard bounds,
beyond which the regexp falls back to the other engines: 12.9 ms and
3.2 MiB.
A cache budget is a cliff. I found this one while writing this post.
The Slack form of the monster wraps every literal in .* and anchors the
whole. Without a match the DFA flew: 4.8 µs against the stdlib’s 3.16 ms.
On the input with a match, v1.11.1 took 7.2 ms against the stdlib’s
3.24 ms, over 2x slower. After the literal matches, every state also
carries the thread waiting for the end of the text. That doubles the
states, to about 1250 of them, 1.43 MB, over the 1 MB budget. So the
search built states, filled the cache, gave up, and the NFA started over,
on every call. v1.11.2 doubles the budget to 2 MB, Rust’s default, and a
test now builds such a regexp and fails if the cache resets. The match
takes 4.9 µs against the stdlib’s 3.40 ms. Every budget has such a cliff
somewhere. What matters is how far away it is and how hard the fall. And
Rob’s advice still stands: drop the .*s and the anchors.
Go’s reflect.DeepEqual has opinions. The stdlib’s TestDeepEqual
requires two regexps compiled from the same source to stay
reflect.DeepEqual after use. So no state that a search fills in may hang
off the Regexp. The DFA lives in a table interned by source, through
weak.Pointer and runtime.AddCleanup, both new in Go 1.24, which is why
the DFA needs Go 1.24. Regexps compiled from the same source share one DFA
and its caches.
Watch the registers, not just the algorithm. Rejecting an input shorter than any match took 4.5 ns against the stdlib’s 3.4. With the DFA code in the same function, the compiler spilled all nine argument registers before the length check. Splitting the check into a function of its own brought it to 2.6 ns. The DFA’s inner loop is a small function of its own for the same reason. Its speed swung from 325 to 510 MB/s with the loop’s alignment.
Code layout is noise you can name. A rebuild that only added a test
function moved Find from 98 to 121 ns. Before believing a 14% regression
on rows that never ran the changed code, compare the functions’ addresses
mod 64 (go tool nm), and rebuild both binaries with
-ldflags=-funcalign=64. Here that took the 14% to under 1%.
Not every benchmark number is a speed. Five of the stdlib’s Match
benchmarks end in $. Searched backward from the end, random text fails
within a few bytes, so a call takes about 40 ns at any size, and benchstat
reports “speeds” of up to 820,000 GiB/s on 32 MB, +3,140,574,240% for one
row. That’s arithmetic, not a scan speed. The scan speed shows on the rows
that read their whole input: 642 MiB/s against the stdlib’s 5.9 for
Match/Hard1, 109x, and 7.3x for Match_onepass_regex.
The numbers that matter
From the stdlib’s own benchmarks, run with make benchstat (eight pinned
CPUs, 20 runs each):
- The API benchmarks (
Find,FindAll,ReplaceAll,Match*, the one-pass ones and more): about 2x as a group.NotLiteral12.5x,MatchClass_InRange16x,OnePassShortA5.7x,FindAllTenMatches2.4x,Find1.4x.AnchoredLiteralLongNonMatchis 4% slower. FindSubmatchonly 2% better: the groups still come from the stdlib’s engines.Compileis even.- Scans: 109x for
Match/Hard1, 7.3x forMatch_onepass_regex. The end-anchoredMatchrows are constant time, as explained above. - The benchmarks game’s regex-redux program, on its 50 MB DNA input: 1.72 s against the stdlib’s 16.99 s, 9.9x.
Where this leaves things
A change proposing a lazy DFA for the standard library is open, for issue 11646, the issue this package’s README has pointed to for years. If something like it lands, most Go programs get faster without changing an import, which would be the best outcome. Until then, modernc.org/regexp is a one-line change:
import "modernc.org/regexp"
Known limits: submatches cost about what they cost in the stdlib.
CompilePOSIX and Longest use the DFA only to decide whether there is a
match. io.RuneReader inputs don’t use it at all. Each concurrent search
takes its own cache, up to 2 MB per direction and regexp, which is worth
knowing in a server with thousands of goroutines and big patterns. And for a pure
list of keywords, Aho-Corasick is still the right tool.
The rewrite was done with Claude Code, Anthropic’s coding agent. The commits say so. I reviewed the design before any code was written, and the stdlib’s tests, the fuzzer and an outside review did the rest. The false match above got past all of us but the review.
The code, the design notes (PLAN.md) and the full benchstat output are at modernc.org/regexp.
Comments
Post a Comment