C-Sharp | Java | Python | Swift | GO | WPF | Ruby | Scala | F# | JavaScript | SQL | PHP | Angular | HTML
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 Codex";
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
But: Some programs simply run all day and therefore startup is not as important.
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.