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
- int length = 10000;
- var beginStamp = DateTime.Now;
- int j = 0;
- int denominator = 0;
- for (int i = length; i >= 0; i--)
- {
- try
- {
- j = i / denominator;
- }
- catch (DivideByZeroException ex)
- {
-
- }
- }
- var endStamp = DateTime.Now - beginStamp;
- Console.WriteLine("Time taken : {0} Milliseconds", endStamp.TotalMilliseconds);
- 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.
- int length = 10000;
- var beginStamp = DateTime.Now;
- int j = 0;
- int denominator = 0;
- for (int i = length; i >= 0; i--)
- {
- if (denominator != 0)
- {
- j = i / denominator;
- }
- else
- {
-
- }
- }
- var endStamp = DateTime.Now - beginStamp;
- Console.WriteLine("Time taken : {0} Milliseconds", endStamp.TotalMilliseconds);
- 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.