Sunday, December 14, 2014

How much does RegexOptions.Compiled improve performance in .NET?

Just how much does the RegexOptions.Compiled flag improve regular expression performance in .NET? The answer: a lot! People have spoken about this before, but below are some more numbers to how you just how much it matters!

Performance Stats

Character Count Regex Pattern
1
[a-z]
3
[b-y].[1-8]
5
[b-y].[c-x].[1-8].[2-7]
7
[b-y].[c-x].[d-w].[1-8].[2-7].[3-6]
9
[b-y].[c-x].[d-w].[e-v].[1-8].[2-7].[3-6].[4-5]

RegexOptions 1 3 5 7 9
None 234176 285067 653016 690282 687343
Compiled 193945 235213 430609 452483 454625
Percent Gain 17% 17% 34% 34% 34%

Test Code

public class RegexPerformanceTests
{
    [Fact]
    public void Test()
    {
        TestPattern("[a-z]");
        TestPattern("[b-y].[1-8]");
        TestPattern("[b-y].[c-x].[1-8].[2-7]");
        TestPattern("[b-y].[c-x].[d-w].[1-8].[2-7].[3-6]");
        TestPattern("[b-y].[c-x].[d-w].[e-v].[1-8].[2-7].[3-6].[4-5]");
    }
 
    private void TestPattern(string pattern)
    {
        Console.WriteLine("--- " + pattern + " ---");
 
        var regex1 = new Regex(pattern);
        TestRegex(regex1);
 
        Console.WriteLine("--- Compiled ---");
 
        var regex2 = new Regex(pattern, RegexOptions.Compiled);
        TestRegex(regex2);
    }
        
    private void TestRegex(Regex regex)
    {
        const int count = 100000;
 
        var sw = Stopwatch.StartNew();
 
        for (var x = 0; x < count; x++)
        {
            var guid = Guid
                .NewGuid()
                .ToString();
 
            regex.IsMatch(guid);
        }
 
        sw.Stop();
        Console.WriteLine(sw.ElapsedTicks);
    }
}

Enjoy,
Tom

No comments:

Post a Comment

Real Time Web Analytics