BENCHMARKS · REGEX
One pattern, three engines: interpreted, compiled, source-generated. Suite and raw reports: github.com/gdhami-net/dotnet-benchmarks.
EmailMatching
The same email pattern over 5,000 mixed lines: interpreted vs Compiled vs source-generated regex.
TAKEAWAY A static [GeneratedRegex] is the right default: compiled-class speed, no startup JIT cost, AOT-compatible. Never new up a Regex per call.
In this run: SourceGen_regex is fastest — 1.8× faster than the baseline.
In this run: SourceGen_regex is fastest — 1.8× faster than the baseline.
RESULTS
| method | net9.0 | net10.0 | ratio | allocated | Δ net10.0 |
|---|---|---|---|---|---|
| Interpreted_regex baseline | 255.2 µs ±1.7 µs | 250.1 µs ±1.9 µs | 1.00× | — | -2% |
| Compiled_regex | 152.5 µs ±554 ns | 148.1 µs ±247 ns | 0.59× | — | -3% |
| SourceGen_regex | 150.0 µs ±1.8 µs | 140.7 µs ±795 ns | 0.56× | — | -6% |
RATIO VS BASELINE · net10.0
THE LEDGER · SAME WORKLOAD ACROSS RELEASES (LOG)
Interpreted_regexCompiled_regexSourceGen_regex
THE CODE BEING MEASURED
Interpreted_regex — what this measures
new Regex(pattern) — interpreted at match time.
[Benchmark (Baseline)]
public int Interpreted_regex()
{
var hits = 0;
foreach (var l in _lines)
if (Interpreted.IsMatch(l)) hits++;
return hits;
}Compiled_regex — what this measures
RegexOptions.Compiled — IL emitted at construction.
[Benchmark]
public int Compiled_regex()
{
var hits = 0;
foreach (var l in _lines)
if (Compiled.IsMatch(l)) hits++;
return hits;
}SourceGen_regex — what this measures
[GeneratedRegex] — C# generated at compile time, AOT-friendly.
[Benchmark]
public int SourceGen_regex()
{
var hits = 0;
foreach (var l in _lines)
if (SourceGen().IsMatch(l)) hits++;
return hits;
}