C# RegexOptions.Compiled

RegexOptions.Compiled often improves performance. With it, regular expressions are executed faster. But there are some tradeoffs—the startup time may increase. And benefits are insignificant in many programs.

Example. This program shows the performance change when using RegexOptions.Compiled for a very simple Regex method call. By passing RegexOptions.Compiled to Regex.Match, we improve performance in this case by approximately 25%.

Note: The results of the Match method are the same 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+");
	var s2 = Stopwatch.StartNew();
	for (int i = 0; i < _max; i++)
	    Match match = Regex.Match(value, @"\d+", RegexOptions.Compiled);
	Console.WriteLine(((double)(s1.Elapsed.TotalMilliseconds * 1000000) /
	    _max).ToString("0.00 ns"));
	Console.WriteLine(((double)(s2.Elapsed.TotalMilliseconds * 1000000) /
	    _max).ToString("0.00 ns"));


1289.84 ns
1024.42 ns

Discussion. There are many considerations in deciding whether to use RegexOptions.Compiled. The first is whether startup time is an issue. If your program starts up too slowly, using RegexOptions.Compiled will make that problem worse.

But: Some programs simply run all day and therefore startup is not as important.

If startup time and execution time are both important for your program, you have to strike a balance to get the best results. It is a good idea to only use RegexOptions.Compiled on regular expressions that are executed 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.

Summary. We saw the performance gain in a tight loop for a simple Regex method call with RegexOptions.Compiled. Further we considered the issue of startup time. We proposed a way to choose which regular expressions should be compiled.