Here we test the performance change with RegexOptions.Compiled. By passing RegexOptions.Compiled to Regex.Match, we improve performance significantly in this case.
using System;
using System.Diagnostics;
using System.Text.RegularExpressions;
const int _max = 1000000;
string value =
"dot net 777 perls";
// Version 1: not compiled.
var s1 = Stopwatch.StartNew();
for (int i = 0; i < _max; i++)
{
Match match = Regex.Match(value, @
"\d+");
}
s1.Stop();
// Version 2: compiled regular expression.
var s2 = Stopwatch.StartNew();
for (int i = 0; i < _max; i++)
{
Match match = Regex.Match(value, @
"\d+", RegexOptions.Compiled);
}
s2.Stop();
Console.WriteLine(((double)(s1.Elapsed.TotalMilliseconds * 1000000) / _max).ToString(
"0.00 ns"));
Console.WriteLine(((double)(s2.Elapsed.TotalMilliseconds * 1000000) / _max).ToString(
"0.00 ns"));
232.98 ns Not compiled
153.67 ns Compiled