Performance: Exception Trapping

codeperformancebookLast year while presenting my Rock Your Code: Code and App Performance in Microsoft .NET session at a conference, one of the attendees asked me if using the When() clause is faster or not when trapping Exceptions. I found the question intriguing, so I set out to do performance testing for his question.

Two Ways of Trapping Exceptions

Ever since .NET was released, this is the normal way of coding exception trapping, something very important in your code to prevent the app or service going down.

try
{
    //Code that could cause an Exception
}
catch (ArgumentNullException argNullEx)
{
    return argNullEx.Message;
}
catch (ArgumentOutOfRangeException argOutOfRangeEx)
{
    return argOutOfRangeEx.Message;
}

The newer and easier way of trapping Exceptions is by using the When() clause like this:

try
{
    //Code that could cause an Exception
}
catch (Exception ex) when (ex is ArgumentNullException || 
                           ex is ArgumentOutOfRangeException)
{
    return ex.Message;
}

As you can see, using the When() clause while trapping similar Exceptions can decrease the amount of code needed to deal with it. So which one should you use when it comes to performance?

Benchmark

Here are the performance results when running the code above on my Microsoft Surface laptop with 16GB of RAM and a virtual machine running 32GB of memory in Microsoft Azure.

Exception Perf.png

Results

As you can see from the charts above that there isn’t much difference using the When clause. The biggest performance difference shown is that the CLR (4.7.2) for some reason is faster than Core (2.2).

So, if you are using .NET Core or thinking about moving to it, my recommendation is to stick with the normal way of trapping exceptions until the .NET Core team works on the performance. I will re-test this when .NET Core 3 is released.

Have a Burning Performance Question?

Do you have a performance question? If so, please leave a comment below or email me by going here: https://dotnettips.wordpress.com/about

Leave a Reply

Please log in using one of these methods to post your comment:

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