The performance cost of C# exceptions: is it true or false?
The exceptional performance of C# has always been controversial. Although the performance loss is not significant when the stack is not deep, various opinions are inconsistent.
Accurate performance testing
To address this issue, we developed a benchmark similar to Jon Skeet’s previous research. The test results show that it takes 29914 milliseconds to handle one million exceptions, which means that approximately 33 exceptions are processed every millisecond. This shows that exceptions are fast enough as an alternative to returning values in most cases.
Comparison with return value
However, when using the return value, the same program completes in less than a millisecond. This means that exceptions are at least 30,000 times slower than return values . It should be noted that these are minimum time-consuming, and it may take more time to actually throw or catch exceptions.
Test environment
Tested on a laptop powered by Intel Core 2 Duo T8100 @ 2.1 GHz, running .NET 4.0 release, without debugger enabled.
Test code
The following code snippet demonstrates performance comparison:
<code class="language-csharp">static void Main(string[] args) { int iterations = 1000000; Console.WriteLine("Starting " + iterations.ToString() + " iterations...\n"); var stopwatch = new Stopwatch(); // 异常测试 stopwatch.Reset(); stopwatch.Start(); for (int i = 1; i <= iterations; i++) { try { // ... 异常代码 ... } catch (Exception) { // ... 异常处理 ... } } stopwatch.Stop(); Console.WriteLine("Exceptions: " + stopwatch.ElapsedMilliseconds + "ms"); // 返回值测试 stopwatch.Reset(); stopwatch.Start(); for (int i = 1; i <= iterations; i++) { // ... 返回值代码 ... } stopwatch.Stop(); Console.WriteLine("Return Codes: " + stopwatch.ElapsedMilliseconds + "ms"); }</code>
(Note: The specific exception code and return value code are omitted here, it is only an example) The complete test code needs to include specific exception throwing and processing logic, as well as return value judgment logic . Only then can a more accurate performance comparison be made.
The above is the detailed content of Are C# Exceptions Really That Much Slower Than Return Codes?. For more information, please follow other related articles on the PHP Chinese website!