16三/100
浅测Try&Catch的性能到底有多差(1)
Hello,我是Snake,欢迎阅读我的文章--浅测Try&Catch的性能到底有多差(1)
今天中午本来是java课老师叫我们用它来实现杨辉三角.当初已经临近下课,由于用不惯Eclipse,一直卡在一个下标越界的错误上,直到下课也没把程序正常运行出来.晚上回宿舍就特别不爽,于是用C#将之重写了一遍,首次测试运行,结果成功.心理稍稍有点欣喜.
由于未来的就业压力,我脑子突然一热,再想未来面试途中如果面试官刚好叫我输出杨辉三角我应该怎么写它比较快,切不容易错呢?在我的办法呈现之前,先把我的算法代码贴上来(由于本人数学的那根筋比较细,算法不一定是最佳算法)
public class MyClass
{
public static void Main()
{
int maxLine=8;
int[][] ns=new int[maxLine][];
for(int i=0;i<maxLine;i++)
{
ns[i]=new int[i+1];
for(int j=0;j<i+1;j++)
{
if(i-1<0)
{
ns[i][j]=1;
continue;
}
else if(j - 1 < 0)
{
ns[i][j]=1;
continue;
}
else if(ns[i-1].Length<j+1)
{
ns[i][j]=1;
continue;
}
else
{
ns[i][j]=ns[i-1][j-1]+ns[i-1][j];
}
}
}
for(int i=0;i<MaxLine;i++)
{
for(int j=0;j<i+1;j++)
{
int t=ns[i][j];
if(t<10)
Console.Write(" ");
Console.Write(t.ToString()+" ");
}
Console.WriteLine("");
}
Console.ReadLine();
}
}
于是结果如下:

是不是相当标准 : )
好了,由于前面的代码有一长串if和else语句,个人认为这个代码丑了点,于是决定直接不判断,直接try和catch一下.于是上面的代码发生的变化:
for(int i=0;i<maxLine;i++)
{
try
{
ns[i][j]=ns[i-1][j-1]+ns[i-1][j];
}
catch
{
ns[i][j]=1;
}
}
现在代码清爽了点.但是由于以前听说过try&catch的性能相当的差,于是谨慎得测试一下性能会比较好,而且到头来还能多长点见识.于是改写代码如下(这时就不输出结果了,只是纯粹后台操作):
public class MyClass
{
public static void Main()
{
int maxLine=10000;
int[][] ns=new int[maxLine][];
Stopwatch sw=new Stopwatch();
for(int t=0;t<5;t++)
{
sw.Reset();
sw.Start();
for(int i=0;i<maxLine;i++)
{
ns[i]=new int[i+1];
for(int j=0;j<i+1;j++)
{
if(i-1<0)
{
ns[i][j]=1;
continue;
}
else if(j - 1 < 0)
{
ns[i][j]=1;
continue;
}
else if(ns[i-1].Length<j+1)
{
ns[i][j]=1;
continue;
}
else
{
ns[i][j]=ns[i-1][j-1]+ns[i-1][j];
}
// try
// {
// ns[i][j]=ns[i-1][j-1]+ns[i-1][j];
// }
// catch(Exception ex)
// {
// ns[i][j]=1;
// }
}
}
sw.Stop();
Console.WriteLine(sw.Elapsed.ToString());
}
Console.ReadLine();
}
}
我先是测试了一下多次if和else的10000行操作:
结果我已经截图下来了:总共10次.


10000万行的总共用时大概在0.5秒左右.而这次我要运行try&catch块的代码:


这个结果果然验证了try&catch性能差的命题了!相差3~4倍的时间!
所以如果您下次要在超级循环中用到try&catch的时候,该谨慎点了.
