RegexOptions.Compiled
This option often improves performance with C# Regex
code. With it, regular expressions are executed faster.
There are some tradeoffs—with Compiled Regex
, startup time will increase. And benefits are insignificant in many programs.
We can use a compiled regular expression in C# by passing RegexOptions.Compiled
to methods like Match
. This will enhance performance if the Match
method is called many times.
using System; using System.Text.RegularExpressions; // Use compiled regex to match word starting with c. var value = "bird cat"; Match match = Regex.Match(value, @"c.+", RegexOptions.Compiled); Console.WriteLine(match.Value);cat
Here we test the performance change with RegexOptions.Compiled
. By passing RegexOptions.Compiled
to Regex.Match
, we improve performance significantly in this case.
Regex.Match
call that does not include the RegexOptions
argument, and thus is not compiled.RegexOptions.Compiled
as the third argument to Match()
.Match()
returns the same values with both calls. The performance is the only difference.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
When should we use RegexOptions.Compiled
? If your program starts up too slowly, using RegexOptions.Compiled
will make that problem worse.
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.
Regex
that is only executed a few times, it is probably not worth compiling it.We saw the performance gain for a simple Regex
method call with RegexOptions.Compiled
. Further we considered the issue of startup time.