Skip to content

Instantly share code, notes, and snippets.

@hypeartist
Last active December 25, 2023 19:54
Show Gist options
  • Save hypeartist/8ffb513d98d12ffb8d5fcd58f581bf94 to your computer and use it in GitHub Desktop.
Save hypeartist/8ffb513d98d12ffb8d5fcd58f581bf94 to your computer and use it in GitHub Desktop.
regexbench.cs
public partial class Bench
{
private const int Rep = 10_000_000;
private readonly Regex _regex = MyRegex();
private readonly string _input = "723402139283478235u7uA874-sdjw4##7fshsjs6763820XSDFww+___43333hnd";
private int _pos = 0;
[Benchmark(Baseline = true)]
public int Test1()
{
var sum = 0;
for (int i = 0; i < Rep; i++)
{
var m = _regex.Match(_input, _pos);
sum += m.Length;
}
return sum;
}
[Benchmark]
public int Test2()
{
var sum = 0;
for (int i = 0; i < Rep; i++)
{
_pos = 0;
var start = _pos;
ReadOnlySpan<char> input = _input;
if (input[_pos] == '0')
{
sum += 1;
continue;
}
while (_pos < input.Length && input[_pos] >= '0' && input[_pos] <= '9')
{
_pos++;
}
sum += _pos - start;
}
return sum;
}
[GeneratedRegex(@"^0|([1-9][0-9]*)")]
private static partial Regex MyRegex();
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment