在企业级开发中使用Try...Catch...会影响效率吗?
记得不久之前,公司一同事曾经说过:“如果是Winform开发,由于程序是在本地,使用try。。。catch不会有太大性能问题,可是如果是在 web服务器上的话,不推荐使用try。。。catch。。。,因为这对于web服务器的性能会有很大影响”。当时我对此一直心存疑问,由于我没有做过测 试,不知道到底是不是这样?所以当时我没有表态。首先我通过Google进行了搜索,有同样想法或同样疑问的人不在少数,表达个人观点的人什么样的都有。 但是从我个人主观上推断,主观推断的结论是:try...catch在没有抛出异常时不影响程序性能,而且即便影响性能,也不见得会成为性能瓶颈。 究竟结果怎样?还是动手写代码做下测试吧。 using ?System.Diagnostics; namespace ?WebApplication3 { ???? public ? static ? class ?Test ????{ ???????? public ? static ? void ?NoTry() ????????{ ???????????? for ?( int ?i? = ? 0 ;?i? < ? 10000 ;?i ++ ) ????????????{ ????????????????System.Web.HttpContext.Current.Response.Write(i.ToString());??????? ????????????} ????????} ???????? public ? static ? void ?HaveTry() ????????{ ???????????? try ????????????{ ???????????????? for ?( int ?i? = ? 0 ;?i? < ? 10000 ;?i ++ ) ????????????????{ ????????????????????System.Web.HttpContext.Current.Response.Write(i.ToString()); ????????????????} ????????????} ???????????? catch (Exception?err) ????????????{ ????????????????System.Web.HttpContext.Current.Response.Write(err.ToString()); ????????????} ???????????? ????????} ???????? public ? static ? long ?HaveException() ????????{ ????????????Stopwatch?sw? = ? new ?Stopwatch(); ????????????sw.Start(); ???????????? try ????????????{ ???????????????? for ?( int ?i? = ? 0 ;?i? < ? 10000 ;?i ++ ) ????????????????{ ????????????????????System.Web.HttpContext.Current.Response.Write(i.ToString()); ????????????????} ???????????????? throw ? new ?Exception( " Kevin让我异常了 " ); ????????????} ???????????? catch ?(Exception?err) ????????????{ ????????????????System.Web.HttpContext.Current.Response.Write(err.ToString()); ????????????} ????????????sw.Stop(); ???????????? return ?sw.ElapsedMilliseconds; ????????} ????} } using ?System.Diagnostics; namespace ?WebApplication3 { ???? public ? partial ? class ?_Default?:?System.Web.UI.Page ????{ ???????? protected ? void ?Page_Load( object ?sender,?EventArgs?e) ????????{ ????????} ???????? protected ? void ?Button1_Click( object ?sender,?EventArgs?e) ????????{ ????????????Stopwatch?sw? = ? new ?Stopwatch(); ????????????sw.Start(); ????????????Test.NoTry(); ????????????sw.Stop(); ????????????lblMessage.Text? = ? " 测量实例得出的总运行时间(毫秒为单位): " ? + ?sw.ElapsedMilliseconds; ????????} ???????? protected ? void ?Button2_Click( object ?sender,?EventArgs?e) ????????{ ????????????Stopwatch?sw? = ? new ?Stopwatch(); ????????????sw.Start(); ????????????Test.NoTry(); ????????????sw.Stop(); ????????????lblMessage.Text? = ? " 测量实例得出的总运行时间(毫秒为单位): " ? + ?sw.ElapsedMilliseconds; ????????} ???????? protected ? void ?Button3_Click( object ?sender,?EventArgs?e) ????????{ ????????????lblMessage.Text? = ?Test.HaveException().ToString(); ????????} ????} } ?测试结果如下表所示: ? |