尝试捕获性能 [英] try catch performance

查看:100
本文介绍了尝试捕获性能的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这在MSDN上文章指出,你可以使用尽可能多的尝试捕捉只要你想,不会产生任何性能开销,只要没有实际的异常被抛出块。结果
因为我始终认为,一个try-catch总是一个小的性能时,不扔的例外,甚至打,我做了一个小测试。

This article on MSDN states that you can use as many try catch blocks as you want and not incur any performance cost as long no actual exception is thrown.
Since I always believed that a try-catch always takes a small performance hit even when not throwing the exception, I made a little test.

 private void TryCatchPerformance()
        {
            int iterations = 100000000;

            Stopwatch stopwatch = Stopwatch.StartNew();
            int c = 0;
            for (int i = 0; i < iterations; i++)
            {
                try
                {
                   // c += i * (2 * (int)Math.Floor((double)i));
                    c += i * 2;
                }
                catch (Exception ex)
                {
                    throw;
                }
            }
            stopwatch.Stop();
            WriteLog(String.Format("With try catch: {0}", stopwatch.ElapsedMilliseconds));

            Stopwatch stopwatch2 = Stopwatch.StartNew();
            int c2 = 0;
            for (int i = 0; i < iterations; i++)
            {
              //  c2 += i * (2 * (int)Math.Floor((double)i));
                c2 += i * 2;
            }
            stopwatch2.Stop();
            WriteLog(String.Format("Without try catch: {0}", stopwatch2.ElapsedMilliseconds));
        }

输出我得到:

With try catch: 68
Without try catch: 34

如此看来,不使用try-catch块似乎是毕竟?_爱快
我觉得更奇怪的是,当我更换计算在体内的for循环通过更复杂的东西,如: C + = I *(2 *(INT)Math.Floor((双)一));
结果不同的是远不如戏剧性。结果

So it seems that using no try-catch block seems to be faster after all?

What I find even more strange is that when I replace the computation in the body of the for-loops by something more complex like: c += i * (2 * (int)Math.Floor((double)i));
The difference is far less dramatic.

With try catch: 640
Without try catch: 655

我是不是错在这里做的事情还是有一个合理的解释这个?

Am I doing something wrong here or is there a logical explanation for this?

推荐答案

的JIT不会对'保护'执行优化/'尝试'块,我想这取决于code你try / catch块写,这会影响你的表现。

The JIT doesn't perform optimization on 'protected' / 'try' blocks and I guess depending on the code you write in try/catch blocks, this will affect your performance.

这篇关于尝试捕获性能的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆