看书的时候想起句话,说C++的异常处理对运行速度有影响(好几年前读书的时候看到的)!然后就想,那java呢?
于是就花了些时间写了测试,测试的代码如:
package cn.along.java.test;
/**
* @author along
* @version 2009-8-18
*/
public class TestExceptionEfficiency
{
public static void main(String[] args)
{
// 首先新建两个ExceptionClass对象,以去除因载入类而需要的时间花费
ExceptionClass test1 = new ExceptionClass();
ExceptionClass test2 = new ExceptionClass();
// 设置两个对象的值
test1.setI(1000);
test2.setI(1000);
// 开始第一个对象的测试
long timeBegin1 = System.currentTimeMillis();
test1.mytest1();//
long timeEnd1 = System.currentTimeMillis();
// 开始第二个对象的测试(含有异常处理)
long timeBegin2 = System.currentTimeMillis();
test2.mytest4();
long timeEnd2 = System.currentTimeMillis();
// 测试结束,计算结果
System.out.println("test1 use time is (time*1000):"
+ ((timeEnd1 - timeBegin1) * 1000) + " timeEnd = " + timeEnd1
+ " timeBegin = " + timeBegin1);
System.out.println("test2 use time is (time*1000):"
+ ((timeEnd2 - timeBegin2) * 1000) + " timeEnd = " + timeEnd2
+ " timeBegin = " + timeBegin2);
/**
* test1 use time is (time*1000):16000 timeEnd = 1250587016859 timeBegin =
* 1250587016843
test2 use time is (time*1000):203000 timeEnd =
* 1250587017062 timeBegin = 1250587016859
*
* 如果采用只申明异常,而不抛出异常来看.两者的执行速度差异性较少.但一但扔出异常,则test2对象的时间将是其10倍.
*/
}
}
//另一个文件.
package cn.along.java.test;
/**
* @author along
* @version 2009-8-18
*/
public class ExceptionClass
{
private int value;
public void setI(int i)
{
this.value = i;
}
/**
* 第一个版本
*
*/
public void mytest1()
{
for (int i = this.value; i > 0; --i)
{
mytest2(this.value);
}
}
/**
* 求1到i的和 : mytest2(i) = i + mytest2(i -1)
*
* @param i
* @return
*/
private int mytest2(int i)
{
if (i == 1)
{
return 1;
}
else
{
return i + this.mytest2(i - 1);
}
}
/**
* 求1到i的和 : mytest3(i) = i + mytest3(i -1)
*
* @param i
* @return
* @throws Exception
* 这个异常只为了测试效率
*/
private int mytest3(int i) throws Exception
{
if (i == 1)
{
// return 1;
throw new Exception("error");
}
else
{
return i + this.mytest3(i - 1);
}
}
/**
* 这个版本只说明,并没有扔出
*
* @param i
* @return
* @throws Exception
*/
private int mytest(int i) throws Exception
{
if (i == 1)
{
return 1;
}
else
{
return i + this.mytest3(i - 1);
}
}
/**
* 第二个版本
*
*/
public void mytest4()
{
for (int i = this.value; i > 0; --i)
{
try
{
this.mytest3(this.value);
}
catch (Exception e)
{
// e.printStackTrace();
}
}
}
/**
* 测试三
*
*/
public void mytest5()
{
for (int i = this.value; i > 0; --i)
{
try
{
this.mytest(this.value);
}
catch (Exception e)
{
// e.printStackTrace();
}
}
}
}
得出的结论已写在main函数中了.此处就不再述了.
抛出异常之后,之所以占用大量时间,有书上的解释是,当异常发生时,java会通过堆栈一路向后查找,能处理此异常的catch()块.
这一段时间是与不发生异常多出来的.
java 异常效率测试测试
最新推荐文章于 2021-08-06 20:24:42 发布
本文通过具体测试案例对比了Java中使用异常处理与未使用异常处理的代码执行效率,结果显示,一旦触发异常,代码的执行时间将显著增加。
1458

被折叠的 条评论
为什么被折叠?



