Using Pattern Matching in C# for Performance Optimization

 
 
  • Gérald Barré

The C# compiler is smart enough to understand some constructs and generates optimized code. However, C# gives you multiple ways to express the same intent. The compiler is not always smart enough to optimize every single ways. In this post, I will show you how to use pattern matching syntax to improve the performance of your code in some cases.

Here's an example that checks if a version number is one of several specific values. You can use different syntaxes to express this check, such as using if statements, switch expressions, or pattern matching syntax.

C#
private static bool Sample1(short version)
    => version == 0x0002
    || version == 0x0300
    || version == 0x0301
    || version == 0x0302
    || version == 0x0303
    || version == 0x0304;

private static bool Sample2(short version)
    => version is 0x0002
               or 0x0300
               or 0x0301
               or 0x0302
               or 0x0303
               or 0x0304;

private static bool Sample3(short version)
    => version switch
    {
        0x0002 or 0x0300 or 0x0301 or 0x0302 or 0x0303 or 0x0304 => true,
        _ => false
    };

You can see that the compiler generates an optimized code for the method that use pattern matching syntax.

C#
private static bool Sample1(short version)
{
    if (version != 2 && version != 768 && version != 769 && version != 770 && version != 771)
    {
        return version == 772;
    }
    return true;
}

private static bool Sample2(short version)
{
    if (version == 2 || (uint)(version - 768) <= 4u)
    {
        return true;
    }
    return false;
}

private static bool Sample3(short version)
{
    if (version == 2 || (uint)(version - 768) <= 4u)
    {
        return true;
    }
    return false;
}

Last but not least, even if the compiler is not able to optimize some code, the JIT can still do the job. Be sure to run a benchmark using BenchmarkDotNet to validate the performance benefits.

Do you have a question or a suggestion about this post? Contact me!

Follow me:
Enjoy this blog?Buy Me A Coffee💖 Sponsor on GitHub