Benchmark. Here we test the performance change with RegexOptions.Compiled. By passing RegexOptions.Compiled to Regex.Match, we improve performance significantly in this case.
Result Match() returns the same values with both calls. The performance is the only difference.
using System;
using System.Diagnostics;
using System.Text.RegularExpressions;
class Program
{
const int _max = 1000000;
static void Main()
{
string value = "dot net 777 perls";
var s1 = Stopwatch.StartNew();
for (int i = 0; i < _max; i++)
{
Match match = Regex.Match(value, @"\d+");
}
s1.Stop();
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 ns153.67 ns
Discussion. When should we use RegexOptions.Compiled? If your program starts up too slowly, using RegexOptions.Compiled will make that problem worse.
But Some programs simply run all day and therefore start up is not as important.
Note, startup time. If start up and execution time are both important, you have to make a tradeoff. Consider only using Compiled on Regexes that are run many times.
Tip For a Regex that is only executed a few times, it is probably not worth compiling it.
And After all, startup time for a program is part of the total execution time.
A summary. We saw the performance gain for a simple Regex method call with RegexOptions.Compiled. Further we considered the issue of startup time.
Dot Net Perls is a collection of tested code examples. Pages are continually updated to stay current, with code correctness a top priority.
Sam Allen is passionate about computer languages. In the past, his work has been recommended by Apple and Microsoft and he has studied computers at a selective university in the United States.