Repository navigation
Regex: prefer searching for the literal after a leading set loop over sets with many characters - #136690
Closed
armanossiloko wants to merge 1 commit into
Closed
Regex: prefer searching for the literal after a leading set loop over sets with many characters#136690armanossiloko wants to merge 1 commit into
armanossiloko wants to merge 1 commit into
Conversation
|
Azure Pipelines: Successfully started running 3 pipeline(s). 13 pipeline(s) were filtered out due to trigger conditions. There may be pipelines that require an authorized user to comment /azp run to run. |
Contributor
|
Tagging subscribers to this area: @dotnet/area-system-text-regularexpressions |
…y chars RegexFindOptimizations prefers searching for a literal that follows a leading set loop (e.g. the '@' in [a-z0-9._%+-]+@...) over searching for the set, unless the set "has Chars", i.e. could be searched with IndexOfAny. That rule was written when Chars held at most 5 characters; #89205 then raised that limit to 128 so that larger sets could use SearchValues, which silently made every enumerable set (e.g. [a-z0-9._%+-], [A-Za-z]) win over the literal. Such sets match almost everywhere in typical text, so patterns like the classic email regex started a match attempt at nearly every position. Restore the original intent: sets of more than 5 characters lose to the literal when the literal starts with ASCII punctuation or a symbol that the frequency table says is at least 4x rarer than the set. Co-Authored-By: Claude Opus 5.5 <[email protected]>
armanossiloko
force-pushed
the
perf/regex-literal-after-loop
branch
from
October 30, 2026 10:58
44944ec to
263a45f
Compare
Author
|
Just cleaning up old issues and PRs. |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Summary
For patterns that begin with a loop over a set of more than a few characters followed by a literal, such as the email pattern
[a-z0-9._%+-]+@[a-z0-9.-]+\.[a-z]{2,},RegexFindOptimizationscurrently searches for the leading set (LeadingSet_LeftToRight). It should search for the literal after the loop (LiteralAfterLoop_LeftToRight). The set matches almost every position of typical text, so a match attempt starts nearly everywhere. Counting matches of that email pattern in 16 MB of text takes 167 ms with the interpreter and 53 ms withRegexOptions.Compiled. With this change both take 1.4 ms.The change is a few lines in
RegexFindOptimizationsand only affects which find mode is chosen. Match results are unchanged.Cause
The selection logic prefers the literal-after-loop search over the best fixed-distance set unless that set has
Chars:When this was written (#89099),
Charswas only populated for sets of at most 5 characters (stackalloc char[5]; // max efficiently optimized by IndexOfAny today), so "hasChars" meant "is a small set". Two days later, #89205 raised that limit to 128 so that larger sets could be searched withSearchValues. As a result every enumerable set now wins over the literal:[a-z0-9._%+-],[A-Za-z],[0-9a-fA-F]and so on.Single-range sets weren't affected, because they get a
Rangeinstead ofChars. That's why[a-z]+@already usesLiteralAfterLoop_LeftToRightwhile[a-z0-9]+@doesn't.Change
A set with more than 5 characters now loses to the literal after the loop, provided:
@,:,(,=,,,.,;,-,%,', …), andSets of up to 5 characters, negated sets, and literals starting with a letter, digit or whitespace are handled exactly as before.
The two guards come from measurements. I first tried a plain frequency comparison and found these slower:
[A-Z0-9]+(followed by a space) ran at 0.45× and[xyzXYZ0-9]+eat 0.61×.[0-9A-F]+hran at 0.29× compiled on English prose. The frequency table is built partly from C# source, so it underestimates letters in prose.Restricting the rule to punctuation and symbols with a 4× margin keeps all of these on the set search.
The source generator shares
RegexFindOptimizations, so it picks the same mode for these patterns. The compiler and source generator already support this mode.Performance
Windows 10 x64, Intel Core i9-9900K.
mainat 72509c6 vs. this PR, both Release builds, differing only inSystem.Text.RegularExpressions.dll. Each number isRegex.Countover a whole text, best of 5 after warmup, median of 4 interleaved runs that alternate the order of the two builds.The texts are the four used by dotnet/performance's regex benchmarks:
3200.txt(16 MB),sherlock.txt(0.6 MB) andmariomka.txt(6.8 MB), plus 7.3 MB of C# source from this repo. Every row was measured with all three engines on all four texts. Times are shown for3200.txt; the last column gives the smallest speedup among the 12 combinations.CompiledNonBacktracking[a-z0-9._%+-]+@[a-z0-9.-]+\.[a-z]{2,}[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}[a-zA-Z0-9]+@[A-Za-z0-9_]+\([0-9a-fA-F]+:[A-Z0-9]+-[0-9]+[A-Za-z]+:[a-zA-Z]+\.[A-Za-z0-9]+=[A-Za-z]+'s[A-Za-z0-9_.]+;[0-9a-f]+-[0-9a-f]+[A-Za-z]+,[A-Z0-9]+\.[0-9.]+,[A-Z0-9_]+=[0-9.]+%Unaffected patterns. No pattern in dotnet/performance's regex benchmarks changes find mode. I compared the chosen mode under both builds for every pattern in
Perf_Regex_Industry_*(RustLang_Sherlock, Mariomkas, Leipzig, BoostDocs_Simple, Rebar_Russian, Rebar_Chinese) andPerf_Regex_Common, including theIgnoreCasevariants. Patterns that keep their mode, such as[A-Z0-9]+,[0-9A-F]+h,[xyzXYZ0-9]+eandSherlock|Holmes, measure 1.00× ± 0.02 in separate processes. A byte-identical copy of the baseline measures the same.When many patterns run in one process, the patterns that keep
LeadingSet_LeftToRightmeasured up to 10–15% slower in this PR's build. This happens when they run after patterns that now useLiteralAfterLoop_LeftToRight. I believe this comes from dynamic PGO profiling the find-modeswitchthe interpreter and NonBacktracking share differently; it doesn't happen in separate processes.In an end-to-end comparison against Go and Rust that counts the email matches above in 6 MB of generated text,
RegexOptions.Compiledgoes from 19.9 ms to 1.5 ms. Rust'sregexcrate takes about 2 ms.Validation
System.Text.RegularExpressions.Unit.Tests(1,065) andSystem.Text.RegularExpressions.Tests(32,161 + 15,944) pass locally against this build. No tests were changed.Benchmark harness
🤖 Generated with Claude Code