Performance - Exception Trapping

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.

  1. try 
  2. {  
  3.     //Code that could cause an Exception  
  4. catch (ArgumentNullException argNullEx) 
  5. {  
  6.     return argNullEx.Message;  
  7. catch (ArgumentOutOfRangeException argOutOfRangeEx)
  8. {  
  9.     return argOutOfRangeEx.Message;  
  10. }
  11.   
  12. The newer and easier way of trapping Exceptions is by using the When() clause like this
  13. try 
  14. {  
  15.     //Code that could cause an Exception  
  16. catch (Exception ex) when(ex is ArgumentNullException || ex is ArgumentOutOfRangeException) 
  17. {  
  18.     return ex.Message;  
  19. }  

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.

Performance - Exception Trapping 
 

Virtual Machine

Here is the test when running the code above on a virtual machine running 32GB of memory in Microsoft Azure.

Performance - Exception Trapping 
 

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.

McCarter Consulting
Software architecture, code & app performance, code quality, Microsoft .NET & mentoring. Available!