这篇MSDN上的文章说:只要没有实际的异常被抛出,你可以使用任意多个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
我在这里做错了什么,还是有一个逻辑上的解释?