龙盟编程博客 | 无障碍搜索 | 云盘搜索神器
快速搜索
主页 > web编程 > asp.net编程 >

在.NET(C#)使用Try...Catch...会影响效率吗?测试一下

时间:2009-12-21 11:47来源:未知 作者:admin 点击:
分享到:
下面测试下在.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...与不使用,看下性能如何:

测试时用到的类

Code [http://www.xueit.com]
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;
        }
    }
}

测试页的代码

Code [http://www.xueit.com]
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();
        }
    }
}

下面请看测试结果。


收藏文章
表情删除后不可恢复,是否删除
取消
确定
图片正在上传,请稍后...
评论内容为空!
还没有评论,快来抢沙发吧!
按钮 内容不能为空!
立刻说两句吧! 查看0条评论
精彩图集

赞助商链接