Skip to content

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
dotnet:mainfrom
armanossiloko:perf/regex-literal-after-loop
Closed

armanossiloko wants to merge 1 commit into
dotnet:mainfrom
armanossiloko:perf/regex-literal-after-loop

Conversation

@armanossiloko

Copy link
Copy Markdown

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,}, RegexFindOptimizations currently 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 with RegexOptions.Compiled. With this change both take 1.4 ms.

The change is a few lines in RegexFindOptimizations and 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:

// If there is a literal after the loop, consider it to be better than a negated set and better than a set with many characters.
if (literalAfterLoop is null ||
    (fixedDistanceSets[0].Chars is not null && !fixedDistanceSets[0].Negated))

When this was written (#89099), Chars was only populated for sets of at most 5 characters (stackalloc char[5]; // max efficiently optimized by IndexOfAny today), so "has Chars" meant "is a small set". Two days later, #89205 raised that limit to 128 so that larger sets could be searched with SearchValues. 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 Range instead of Chars. That's why [a-z]+@ already uses LiteralAfterLoop_LeftToRight while [a-z0-9]+@ doesn't.

Change

A set with more than 5 characters now loses to the literal after the loop, provided:

  • the literal starts with ASCII punctuation or a symbol (@, :, (, =, ,, ., ;, -, %, ', …), and
  • the existing frequency table rates that character at least 4× rarer than the set as a whole.

Sets 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:

  • Literal about as common as the set: with the compiled engine, [A-Z0-9]+ (followed by a space) ran at 0.45× and [xyzXYZ0-9]+e at 0.61×.
  • Letter literals in prose: [0-9A-F]+h ran 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. main at 72509c6 vs. this PR, both Release builds, differing only in System.Text.RegularExpressions.dll. Each number is Regex.Count over 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) and mariomka.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 for 3200.txt; the last column gives the smallest speedup among the 12 combinations.

pattern interpreter Compiled NonBacktracking slowest of the 12
[a-z0-9._%+-]+@[a-z0-9.-]+\.[a-z]{2,} 167.2 → 1.5 ms (115×) 52.6 → 1.4 ms (37×) 86.0 → 1.4 ms (60×) 37.1× (Compiled, 3200)
[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,} 167.0 → 1.4 ms (116×) 53.4 → 1.4 ms (38×) 98.8 → 1.4 ms (70×) 29.0× (Compiled, source)
[a-zA-Z0-9]+@ 170.0 → 1.4 ms (121×) 54.7 → 1.4 ms (38×) 98.8 → 1.5 ms (67×) 29.3× (Compiled, source)
[A-Za-z0-9_]+\( 169.0 → 1.4 ms (119×) 54.4 → 1.4 ms (39×) 99.5 → 1.4 ms (70×) 4.5× (NonBacktracking, source)
[0-9a-fA-F]+: 173.6 → 1.6 ms (106×) 58.6 → 1.5 ms (39×) 95.9 → 1.7 ms (56×) 21.9× (Compiled, mariomka)
[A-Z0-9]+-[0-9]+ 37.7 → 2.5 ms (15×) 9.0 → 2.2 ms (4.1×) 29.2 → 2.4 ms (12×) 4.1× (Compiled, 3200)
[A-Za-z]+: 169.3 → 2.1 ms (80×) 54.7 → 1.7 ms (33×) 99.6 → 2.3 ms (44×) 10.6× (Compiled, mariomka)
[a-zA-Z]+\. 169.7 → 13.5 ms (13×) 57.5 → 7.0 ms (8.2×) 104.1 → 16.3 ms (6.4×) 3.5× (NonBacktracking, source)
[A-Za-z0-9]+= 170.1 → 1.4 ms (120×) 54.7 → 1.4 ms (39×) 99.1 → 1.4 ms (70×) 15.2× (Compiled, source)
[A-Za-z]+'s 175.1 → 3.4 ms (51×) 54.8 → 2.5 ms (22×) 100.1 → 3.7 ms (27×) 20.3× (Compiled, mariomka)
[A-Za-z0-9_.]+; 169.1 → 4.1 ms (42×) 55.2 → 2.5 ms (22×) 100.3 → 4.6 ms (22×) 10.4× (Compiled, source)
[0-9a-f]+-[0-9a-f]+ 168.7 → 3.2 ms (52×) 56.7 → 2.5 ms (23×) 94.0 → 3.0 ms (32×) 15.5× (Compiled, mariomka)
[A-Za-z]+, 171.3 → 19.2 ms (8.9×) 59.0 → 9.7 ms (6.1×) 107.3 → 23.5 ms (4.6×) 4.4× (NonBacktracking, sherlock)
[A-Z0-9]+\. 38.0 → 3.8 ms (9.9×) 9.2 → 3.1 ms (3.0×) 29.5 → 3.9 ms (7.6×) 3.0× (Compiled, 3200)
[0-9.]+, 29.1 → 4.2 ms (6.9×) 4.4 → 3.6 ms (1.2×) 25.2 → 4.2 ms (6.0×) 1.2× (Compiled, 3200)
[A-Z0-9_]+= 37.4 → 1.4 ms (26×) 9.0 → 1.4 ms (6.4×) 29.3 → 1.4 ms (20×) 6.4× (Compiled, 3200)
[0-9.]+% 28.9 → 1.4 ms (20×) 4.3 → 1.4 ms (3.1×) 25.1 → 1.5 ms (17×) 3.1× (Compiled, 3200)

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) and Perf_Regex_Common, including the IgnoreCase variants. Patterns that keep their mode, such as [A-Z0-9]+ , [0-9A-F]+h, [xyzXYZ0-9]+e and Sherlock|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_LeftToRight measured up to 10–15% slower in this PR's build. This happens when they run after patterns that now use LiteralAfterLoop_LeftToRight. I believe this comes from dynamic PGO profiling the find-mode switch the 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.Compiled goes from 19.9 ms to 1.5 ms. Rust's regex crate takes about 2 ms.

Validation

  • System.Text.RegularExpressions.Unit.Tests (1,065) and System.Text.RegularExpressions.Tests (32,161 + 15,944) pass locally against this build. No tests were changed.
  • Match counts are identical between the two builds for every pattern, engine and text in the table.
Benchmark harness
var re = new Regex(pattern, options);
int c = re.Count(text);                                   // warmup + correctness check
var w = Stopwatch.StartNew();
while (w.ElapsedMilliseconds < 200) re.Count(text);       // let tiering settle
double best = double.MaxValue;
for (int i = 0; i < 5; i++) { var sw = Stopwatch.StartNew(); re.Count(text); best = Math.Min(best, sw.Elapsed.TotalMilliseconds); }

🤖 Generated with Claude Code

@dotnet-policy-service dotnet-policy-service Bot added the community-contribution Indicates that the PR has been added by a community member label Oct 30, 2026
@azure-pipelines

Copy link
Copy Markdown
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.

@dotnet-policy-service

Copy link
Copy Markdown
Contributor

Tagging subscribers to this area: @dotnet/area-system-text-regularexpressions
See info in area-owners.md if you want to be subscribed.

…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

Copy link
Copy Markdown
Author

Just cleaning up old issues and PRs.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

area-System.Text.RegularExpressions community-contribution Indicates that the PR has been added by a community member

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant