不抛出异常时,try/catch 块是否会影响性能? [英] Do try/catch blocks hurt performance when exceptions are not thrown?
问题描述
在与 Microsoft 员工进行代码审查期间,我们在 try{}
块中发现了一大段代码.她和一位 IT 代表建议这会对代码的性能产生影响.事实上,他们建议大部分代码应该在 try/catch 块之外,并且只应该检查重要的部分.微软员工补充说,即将发布的白皮书警告不正确的 try/catch 块.
During a code review with a Microsoft employee we came across a large section of code inside a try{}
block. She and an IT representative suggested this can have effects on performance of the code. In fact, they suggested most of the code should be outside of try/catch blocks, and that only important sections should be checked. The Microsoft employee added and said an upcoming white paper warns against incorrect try/catch blocks.
我环顾四周,发现它可以影响优化,但它似乎只适用于在范围之间共享变量的情况.
I've looked around and found it can affect optimizations, but it seems to only apply when a variable is shared between scopes.
我不是在问代码的可维护性,甚至不是处理正确的异常(毫无疑问,有问题的代码需要重构).我也不是指使用异常进行流量控制,这在大多数情况下显然是错误的.这些都是重要的问题(有些更重要),但不是这里的重点.
I'm not asking about maintainability of the code, or even handling the right exceptions (the code in question needs re-factoring, no doubt). I'm also not referring to using exceptions for flow control, this is clearly wrong in most cases. Those are important issues (some are more important), but not the focus here.
当不抛出异常时,try/catch块如何影响性能?
How do try/catch blocks affect performance when exceptions are not thrown?
推荐答案
检查一下.
static public void Main(string[] args)
{
Stopwatch w = new Stopwatch();
double d = 0;
w.Start();
for (int i = 0; i < 10000000; i++)
{
try
{
d = Math.Sin(1);
}
catch (Exception ex)
{
Console.WriteLine(ex.ToString());
}
}
w.Stop();
Console.WriteLine(w.Elapsed);
w.Reset();
w.Start();
for (int i = 0; i < 10000000; i++)
{
d = Math.Sin(1);
}
w.Stop();
Console.WriteLine(w.Elapsed);
}
输出:
00:00:00.4269033 // with try/catch
00:00:00.4260383 // without.
以毫秒为单位:
449
416
新代码:
for (int j = 0; j < 10; j++)
{
Stopwatch w = new Stopwatch();
double d = 0;
w.Start();
for (int i = 0; i < 10000000; i++)
{
try
{
d = Math.Sin(d);
}
catch (Exception ex)
{
Console.WriteLine(ex.ToString());
}
finally
{
d = Math.Sin(d);
}
}
w.Stop();
Console.Write(" try/catch/finally: ");
Console.WriteLine(w.ElapsedMilliseconds);
w.Reset();
d = 0;
w.Start();
for (int i = 0; i < 10000000; i++)
{
d = Math.Sin(d);
d = Math.Sin(d);
}
w.Stop();
Console.Write("No try/catch/finally: ");
Console.WriteLine(w.ElapsedMilliseconds);
Console.WriteLine();
}
新结果:
try/catch/finally: 382
No try/catch/finally: 332
try/catch/finally: 375
No try/catch/finally: 332
try/catch/finally: 376
No try/catch/finally: 333
try/catch/finally: 375
No try/catch/finally: 330
try/catch/finally: 373
No try/catch/finally: 329
try/catch/finally: 373
No try/catch/finally: 330
try/catch/finally: 373
No try/catch/finally: 352
try/catch/finally: 374
No try/catch/finally: 331
try/catch/finally: 380
No try/catch/finally: 329
try/catch/finally: 374
No try/catch/finally: 334
这篇关于不抛出异常时,try/catch 块是否会影响性能?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!