jehn

异常处理的性能损失

using System;
using System.Text;

namespace 异常处理的性能损失
{
    /// <summary>
    /// C# 异常处理性能损耗
    /// 代码作者:jehnjehn
    /// Email:jehn@foxmail.com
    /// 【jehnjehn推荐的原则:尽可能避免异常而不是捕获并处理异常】
    /// </summary>
    class Program
    {
        static void Main(string[] args)
        {
            int testTimes = 10000;//自定义测试次数。
            StringBuilder sb = new StringBuilder(string.Concat("执行", testTimes,
                "次循环运算时,几种异常处理方式性能对比(按运行时间越短性能越高)"));
            sb.AppendLine(Environment.NewLine);
            System.Diagnostics.Stopwatch w = new System.Diagnostics.Stopwatch();



            //方式一:避免异常而非捕获异常
            int a = 0;
            w.Start();
            for (int i = 0; i <= testTimes; i++)
            {
                Int32.TryParse("a", out a);
            }
            w.Stop();
            sb.AppendLine(string.Concat("TypParse避免异常:", w.ElapsedMilliseconds, "ms"));



            //屏蔽所有异常,这种脑残的写法仅供测试
            w.Reset();
            w.Start();
            for (int i = 0; i <= testTimes; i++)
            {
                try
                {
                    Int32.Parse(null);
                }
                catch { }
            }
            w.Stop();
            sb.AppendLine(string.Concat("屏蔽式捕获所有异常:", w.ElapsedMilliseconds, "ms"));



            //抛出指定的异常实例
            w.Reset();
            w.Start();
            for (int i = 0; i <= testTimes; i++)
            {
                try
                {
                    if (!Int32.TryParse("a", out a))
                    {
                        throw new ArgumentNullException(i.ToString());
                    }
                }
                catch { }
            }
            w.Stop();
            sb.AppendLine(string.Concat("抛出指定的异常实例:", w.ElapsedMilliseconds, "ms"));



            //静态异常变量,仅测试
            int b = 0;
            Exception ex = new Exception();
            w.Reset();
            w.Start();
            for (int i = 0; i <= testTimes; i++)
            {
                try
                {
                    if (!Int32.TryParse("a", out b))
                    {
                        throw ex;
                    }
                }
                catch { }
            }
            w.Stop();
            sb.AppendLine(string.Concat("抛出静态异常:", w.ElapsedMilliseconds, "ms\n"));


            Console.WriteLine(sb);
            System.IO.File.WriteAllText("result.txt", sb.ToString());
            Console.WriteLine("Press any key to continue . . . ");
            System.Diagnostics.Process.Start("result.txt");
            //Console.ReadKey(true);
        }
    }
}

结果如下:
执行10000次循环运算时,几种异常处理方式性能对比(按运行时间越短性能越高)TypParse避免异常:1ms屏蔽式捕获所有异常:836ms抛出指定的异常实例:326ms抛出静态异常:185ms

posted on 2011-12-20 17:05  jehn  阅读(320)  评论(0编辑  收藏  举报

导航