throw Exception 的执行效率试验
为了说服当前维护的项目改用 Exception 处理错误,要弄一个异常效率的数据出来。唉…………
- 测试代码
/**
* 异常效率测试
* @throws Exception
*/
@Test
public void testThrowEfficiency() throws Exception {
long times = 1000000;
long startTime;
System.out.println(times + "循环测试");
try {
recursion(0, true);
}
catch (Exception e) {
System.out.println("异常堆栈深度:" + e.getStackTrace().length);
}
for(int count = 0; count < 10; count++) {
startTime = System.currentTimeMillis();
for (int i = 0; i < times; i++) {
try {
recursion(0, true);
}
catch (Exception e) {
}
}
System.out.println("有异常存在:" + (System.currentTimeMillis() - startTime));
startTime = System.currentTimeMillis();
for (int i = 0; i < times; i++) {
try {
recursion(0, false);
}
catch (Exception e) {
}
}
System.out.println("无:" + (System.currentTimeMillis() - startTime));
}
}
private void recursion(int count, boolean isThrow) {
if(count == 10) {
if(isThrow) {
throw new IllegalStateException("");
}
return;
}
recursion(count+1, isThrow);
}
public static void main(String[] args) throws Exception {
Test test = new MakeKeyNoTest();
test.testThrowEfficiency();
}
- 测试机器:
cpu:赛扬 CeleronM CPU 520 @ 1.60GHz(我可怜的机器……)
内存:2GB
- 测试结果:(时间:毫秒)
BODY { FONT-FAMILY:Tahoma; FONT-SIZE:10pt } P { FONT-FAMILY:Tahoma; FONT-SIZE:10pt } DIV { FONT-FAMILY:Tahoma; FONT-SIZE:10pt } TD { FONT-FAMILY:Tahoma; FONT-SIZE:10pt }
1000000循环测试
异常堆栈深度:13
有异常存在:2766
无:47
有异常存在:2890
无:47
有异常存在:2719
无:47
有异常存在:2718
无:47
有异常存在:2688
无:47
有异常存在:2718
无:47
有异常存在:2703
无:32
有异常存在:2672
无:63
有异常存在:2703
无:47
有异常存在:2703
无:31 1000000循环测试
异常堆栈深度:23
有异常存在:3688
无:94
有异常存在:3593
无:94
有异常存在:3625
无:94
有异常存在:3625
无:78
有异常存在:3922
无:94
有异常存在:5625
无:437
有异常存在:8469
无:94
有异常存在:4390
无:94
有异常存在:3594
无:109
有异常存在:3610
无:93 1000000循环测试
异常堆栈深度:33
有异常存在:5328
无:141
有异常存在:5109
无:125
有异常存在:5109
无:157
有异常存在:5093
无:141
有异常存在:12563
无:125
有异常存在:5125
无:125
有异常存在:5218
无:125
有异常存在:5172
无:141
有异常存在:5125
无:140
有异常存在:5204
无:125 1000000循环测试
异常堆栈深度:53
有异常存在:6172
无:234
有异常存在:6063
无:219
有异常存在:6031
无:234
有异常存在:6094
无:234
有异常存在:6078
无:219
有异常存在:6047
无:219
有异常存在:6062
无:235
有异常存在:6031
无:250
有异常存在:6156
无:235
有异常存在:6062
无:234
结果分析:
- 堆栈深度对速度影响很大,基本上呈线性增长。
- 在13层堆栈深度的情况下 耗时约2.7秒,折算每次异常用时 2.7微妙,及普通机器每秒可运行异常抛出37万次。
异常的效率比我以前想象的还要高。