Home
Search
C# RegexOptions.CompiledUse the Regex.Match method with RegexOptions.Compiled to improve matching speed.
dot net perls
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.
Regex
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.
C# program that benchmarks RegexOptions.Compiled
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.
Home
© 2007-2021 sam allen. see site info on the changelog