在.NET(C#)使用Try...Catch...会影响效率吗?测试一下
下面测试下在.NET使用Try...Catch...与不使用,看下性能如何: 测试时用到的类 Code [http://www.xueit.com] using System; using System.Diagnostics; namespace WebApplication3{ public static class Test { public static void
下面测试下在.NET使用Try...Catch...与不使用,看下性能如何:
测试时用到的类

using System; 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; 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(); } } }
下面请看测试结果。
精彩图集
精彩文章
热门标签
代码规范
MVVM
ISNULL
用户安全
WEB表单
不损失透明色
.net
单元测试
mytop
SQL语句
父进程
命令行
多进程同步
数据库镜像
单用户登录
页面跳转
目标文件更新
导致ASP.N
调用方
密码处理
关系数据库
2种
关闭本窗口
Mongodb一些命令
分治假币
php php在一
1-byte
非贪婪模式
表损坏
java分布式
移出节点
前导0
python日期
它在
层飘出
grub启动项
glob
去空格
字符串长度
指令大全
阻止泄漏
表名
数据加解密
size
tinyxml
静态局部变量
图片自定
菱形
手游
strip
handler
chroot
JVM
gb2312
新增元素
编译参数
是否删除
CPU温度
纵表
更简单
赞助商链接
@CopyRight 2002-2008, 1SOHU.COM, Inc. All Rights Reserved QQ:1010969229