java try 性能损耗_异常处理的性能损失

using System;

using System.Text;

namespace 异常处理的性能损失

{

///

/// C# 异常处理性能损耗

/// 代码作者:jehnjehn

/// Email:jehn@foxmail.com

/// 【jehnjehn推荐的原则:尽可能避免异常而不是捕获并处理异常】

///

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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值