核实。
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/catch00:00:00.4260383 // without.
以毫秒为单位:
449416
新代码:
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: 382No try/catch/finally: 332 try/catch/finally: 375No try/catch/finally: 332 try/catch/finally: 376No try/catch/finally: 333 try/catch/finally: 375No try/catch/finally: 330 try/catch/finally: 373No try/catch/finally: 329 try/catch/finally: 373No try/catch/finally: 330 try/catch/finally: 373No try/catch/finally: 352 try/catch/finally: 374No try/catch/finally: 331 try/catch/finally: 380No try/catch/finally: 329 try/catch/finally: 374No try/catch/finally: 334



