Impact of Try-Catch on Performance

In the earlier days of my programming career my lead would insist that our team use if-else statements instead of try-catch block to handle the known or expected exceptions  to gain performance, which made me think what is the difference when we write same number of lines of code, and how much performance we could gain if try-catch is being replaced. As this question is being asked frequently by others, I want to share some sample pieces of code I have written to show the difference in performance.

As you all know when we have try-catch in the code and there is an exception raised then the controller jumps to catch block and executes whatever we have written in catch block, but behind the scenes there is much work done to propagate exceptions through upper layers. It propagates through the entire call stack /memory stack which is an expensive operation and takes a lot of CPU resources internally.

Let us see the execution time difference between try-catch and if-else for the same logic.

try-catch

  1. int length = 10000;  
  2. var beginStamp = DateTime.Now;  
  3. int j = 0;  
  4. int denominator = 0;  
  5. for (int i = length; i >= 0; i--)  
  6. {  
  7.     try  
  8.     {  
  9.         j = i / denominator;  
  10.     }  
  11.     catch (DivideByZeroException ex)  
  12.     {  
  13.         // Logic to handle when denominator is zero  
  14.     }  
  15. }  
  16. var endStamp = DateTime.Now - beginStamp;  
  17. Console.WriteLine("Time taken : {0} Milliseconds", endStamp.TotalMilliseconds);  
  18. Console.ReadLine();  


If-else

Now I’m rewriting the code for the same logic with if-else conditions, we will see the huge gain in speed in the execution time.
  1. int length = 10000;  
  2. var beginStamp = DateTime.Now;  
  3. int j = 0;  
  4. int denominator = 0;  
  5. for (int i = length; i >= 0; i--)  
  6. {  
  7.     if (denominator != 0)  
  8.     {  
  9.         j = i / denominator;  
  10.     }  
  11.     else  
  12.     {  
  13.         // Logic to handle when denominator is zero  
  14.     }  
  15. }  
  16. var endStamp = DateTime.Now - beginStamp;  
  17. Console.WriteLine("Time taken : {0} Milliseconds", endStamp.TotalMilliseconds);  
  18. Console.ReadLine();  


Here it is just checking the denominator variable value against zero ‘0’ and it is not propagating to any call stack. We can see the execution completed in about 1 millisecond which is almost nothing comparative to 28798 milliseconds.

For best practices avoid throwing exceptions as much as possible.