Speed Test: Try / Catch Block
The try/catch block is used to capture thrown exceptions and to allow an application to recover gracefully from the problems that caused them. This article has been created to determine if the try/catch block causes a substantial performance penalty.
This test was designed to determine the performance impact of adding a try/catch block to C# code. The article does not seek to determine why any performance loss occurs from the use of exception handling code, only to measure it.
Test Process Functionality
A simple loop was created that reads and writes to class-level variables within a console application. The functionality of the loop was not deemed to be important, as long at it remained the same for execution with and without the exception handling code. The loop was executed one hundred million times and the difference in duration between the following three variations was measured:
- Execution of the loop with no error handling code.
- Execution of the loop with a try/catch block containing a single catch.
- Execution of the loop with a try/catch block containing multiple catches.
The timing of the tests was controlled automatically using the Stopwatch class. Each test was performed repeatedly and the mean average of the results calculated.
The test results shown in the table below are those produced using an Athlon64 3200+ with 2GB RAM. These tests are indicative of further relative test results that were carried out on a variety of equipment.
The tests were executed using three operating systems, each with the latest service packs and patches. These were:
- Windows XP
- Windows Server 2003 R2
- Windows Vista Ultimate
The test application was developed using C# targeted at the .NET framework 3.5.
This table shows the average timings for the loops for each of the three tests. The first columns show the timing for the entire one hundred million iterations for each test. The second column shows a comparison between the loop time and the timing for the loop without exception handling. The final column shows the average difference for a single try/catch block execution.
|Single Catch||2.94s||0.25s||0.0025 microseconds|
|Multiple Catches||2.95s||0.26s||0.0026 microseconds|
The results show that the use of try/catch blocks does indeed have a performance impact on the software. However, it is very unusual to perform such a large number of iterations with a try/catch block defined within the loop; it would usually be best practise for the entire loop to be executed within a single try block. The performance impact per try/catch block iteration is extremely small and only in the most performance-critical circumstances should the removal of exception handling be considered.
22 June 2008