C# : Pattern Matching vs Performance

Pattern Matching was a hot thing when it was introduced in C# 7.0. It has been really useful and provided a expressive manner when programming. But what about the performance of Pattern Matching? I am discussing about it in this post.

pattern_match.PNG

I took pattern matching switch statements for the post, so this is a valid C# 7.0 code, which used pattern matching in the switch statement.

namespace PatternMatchX
{
    public class Machina
    {
        public void OpX(object oper)
        { 
            switch (oper)
            {
                case DB d:
                    d.Init();
                    break;
                case VM v:
                    v.Boot();
                    break;
                default:
                    break;
            }
        }
    }

    public struct VM
    {
        public void Boot() {}
    }

    public struct DB
    {
        public void Init() { }
    }
}

An identical code to the above code in C# prior to 7.0 can be something like below

namespace PatternMatchW
{
    public class Machina
    {
        public void OpX(object oper)
        {
            switch (oper.GetType().Name)
            {
                case "DB":
                    DB d = (DB)oper;
                    d.Init();
                    break;
                case "VB":
                    VM v = (VM)oper;
                    v.Boot();
                    break;
                default:
                    break;
            }
        }
    }

    public struct VM
    {
        public void Boot() { }
    }

    public struct DB
    {
        public void Init() { }
    }
}

In this code we are using a trick to get the Name of the type as C# prior to 7.0 expects a switch expression or case label represented with a bool, char, string, integral, enum, or corresponding nullable type.

Right after building the above two codes, I have inspected the IL codes for both libraries, a very obvious change was the IL code for which is corresponding to pattern matching carried 58 instructions while the traditional one managed to finish the work in just 51 instructions. The additional 7 lines of code was to ensure the dynamism of pattern matching. isinst was used for the purpose. Mean while in the traditional code, its just a bool check.

Happy Coding..!

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s