c# - 尝试捕捉性能

标签 c# performance

This MSDN 上的文章指出,只要没有抛出实际异常,您就可以使用任意数量的 try catch block ,并且不会产生任何性能成本。
因为我一直相信 try-catch 即使不抛出异常也会对性能造成很小的影响,所以我做了一个小测试。

 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 block 似乎毕竟更快?

我发现更奇怪的是,当我用更复杂的东西替换 for 循环主体中的计算时: c += i * (2 * (int)Math.Floor((double)i) );
差异远没有那么显着。

With try catch: 640
Without try catch: 655

我是不是做错了什么,或者对此有合理的解释吗?

最佳答案

JIT 不会对“protected”/“try” block 执行优化,我猜根据您在 try/catch block 中编写的代码,这会影响您的性能。

关于c# - 尝试捕捉性能,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1350264/

相关文章:

sql-server - 是否使用blob,性能问题

c# - .NET Framework 4.x 中的插件系统安全性(无 CAS)

c# - ASP.Net/C# 将 NameValueCollection 转换为 IDictionary?

c# - 使用 EWS 和 C# 获取附件失败并出现 ServiceMethodException

python - 将第一个数组的每个元素与第二个数组的所有元素相加

performance - 快速矢量化 rsqrt 并根据精度与 SSE/AVX 互惠

java - 通过反射在 Java 中调用 getter : What's the fastest way to repeatedly call it (performance and scalability wise)?

python - 如何过滤掉两个巨大列表的列表项?

c# - 将\r 后面没有\n 的所有实例替换为\r\n 的正则表达式

c# - 为什么我在使用 FormulaArray 时不断收到 COM 异常