RegexOptions.CompiledUse the Regex.Match method with RegexOptions.Compiled to improve matching speed.
RegexOptions.Compiled. This option often improves performance with C# Regex code. With it, regular expressions are executed faster.
Compiled tradeoffs. But there are some tradeoffs—with Compiled Regex, startup time will increase. And benefits are insignificant in many programs.
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 ns 153.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.
No updates found for this page.
© 2007-2023 Sam Allen.