Performance: Exception Trapping
Last 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
- {
-
- }
- 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
- {
-
- }
- 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?
Laptop
Here are the performance results when running the code above on my Microsoft Surface laptop with 16GB of RAM.
Virtual Machine
Here is the test when running the code above on a virtual machine running 32GB of memory in Microsoft Azure.
Results
As you can see from the charts above, 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). Almost double the difference.
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.