C# RegexOptions.Compiled

Regex type

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.

Performance test

Performance optimization

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%. The results of the Match method are exactly the same with both calls.

This C# program uses the Regex.Match method with RegexOptions.Compiled.

Program that benchmarks RegexOptions.Compiled [C#]

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"));
	Console.Read();
    }
}

Output

1289.84 ns
1024.42 ns

Recommendation

This section provides information

There are several considerations you should have when deciding whether to use RegexOptions.Compiled. The first is whether startup time is an issue for your program. If your program starts up too slowly, using RegexOptions.Compiled will make that problem worse. Some programs, though, 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 probably a good idea to only use RegexOptions.Compiled on regular expressions that are executed many times. For a Regex that is only executed a few times, it is probably not worth compiling it. After all, startup time for a program is part of the total execution time.

Summary

The C# programming language

We saw the performance gain during execution in a tight loop for a very simple Regex method call with RegexOptions.Compiled. Further, we considered the issue of startup time and also proposed a way to choose which regular expressions should be compiled, yielding a good balance between fast startup and speedy execution.

Regex Type
.NET