using System;
using System.Text;
namespace 異常處理的性能損失
{
/// <summary>
/// C# 異常處理性能損耗
/// 代碼作者:jehnjehn
/// Email:[email protected]
/// 【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
摘自 欲將心事訴東風,無怨滿城風得意~