This http://msdn.microsoft.com/en-us/library/ms973839.aspx?ppud=4MSDN 上的文章指出,只要没有抛出实际的异常,您可以根据需要使用任意数量的 try catch 块,并且不会产生任何性能成本。
因为我一直相信即使不抛出异常,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 块似乎更快?
我发现更奇怪的是,当我用更复杂的东西替换 for 循环体中的计算时,例如:c += i * (2 * (int)Math.Floor((double)i));
差异远没有那么显着。
With try catch: 640
Without try catch: 655
我在这里做错了什么还是有一个合乎逻辑的解释?
JIT 不会对“受保护”/“尝试”块执行优化,我想根据您在 try/catch 块中编写的代码,这会影响您的性能。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)