The C# compiler understands certain constructs and generates optimized code for them. However, C# offers multiple ways to express the same intent, and the compiler does not always optimize every approach equally. This post shows how to use pattern matching syntax to improve performance 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
};
As shown above, the compiler generates optimized code for methods 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;
}
Even when the compiler cannot optimize certain code, the JIT may still do so. Use BenchmarkDotNet to validate any performance assumptions.
Do you have a question or a suggestion about this post? Contact me!