在与Microsoft员工进行代码审查期间,我们在一个try{}块内遇到了很大一部分代码。她和一位IT代表建议,这可能会影响代码的性能。实际上,他们建议大多数代码应位于try / catch块之外,并且仅应检查重要部分。微软员工补充说,即将发布的白皮书警告不要尝试错误的try / catch块。
try{}
我环顾四周,发现它会影响优化,但似乎仅在范围之间共享变量时才适用。
我不是在问代码的可维护性,甚至不是在处理正确的异常(毫无疑问,有问题的代码都需要重构)。我也不是指使用异常进行流控制,这在大多数情况下显然是错误的。这些是重要的问题(有些更重要),但这里不是重点。
不 抛出异常时,try / catch块如何影响性能?
核实。
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