更新时间:2023-11-29 08:13:34
使用异常处理空检查,边界检查,文件存在检查等操作会在抛出异常时引入大量开销。
Using exceptions for handling operations like null checking, bounds checking, file existance checking introduces a lot of overhead whenever the exception is thrown.
如果您只是检查边界,您会做什么:
What you would have done if you simply checked the bounds:
使用基于异常的检查时您实际在做什么:
What you actually are doing when using exception-based checking:
通过这个简单的测试程序,我测量了两种类型的数组边界检查的速度。
With this simple test program, I have measured the speed of both types of array boundary checks.
public class BoundsCheckTest {
final static int[] array = new int[1];
final static Random gen = new Random();
public static void main(String[] args){
boolean ret = false;
int tries = 100000000;
long timestart = System.nanoTime();
for (int a=0; a< tries; a++) {
ret = method1();
}
long timeend1 = System.nanoTime();
System.out.println();
for (int a=0; a< tries; a++) {
ret = metod2();
}
long timeend2 = System.nanoTime();
System.out.println();
long t1 = timeend1-timestart;
long t2 = timeend2-timeend1;
System.out.println("\ntime 1=["+t1+"]\n 2=["+t2+"]"+
"\ndiff=["+Math.abs(t1-t2)+"] percent diff=["+(100d*t2/t1-100)+"]");
}
private static boolean metod2() {
try {
int val = array[gen.nextInt(2)];
return true;
} catch (Exception e) {
return false;
}
}
private static boolean method1() {
return array.length < gen.nextInt(2);
}
}
结果:
JDK 7,eclipse 以
模式运行:
JDK 7, eclipse Run as
mode:
time check=[911620628]
exc=[1192569638]
diff=[280949010] percent diff=[30.818632375220886]
JDK 7,eclipse 调试
模式:
JDK 7, eclipse Debug
mode:
time check=[931243924]
exc=[651480777121]
diff=[650549533197] percent diff=[69858.12378809143]
禁用调试时的速度损失不是很显着,尽管它是可见的:没有例外的代码速度提高了约30%(大约50%的错误回报)。调试模式下的速度损失是惊人的。基于异常的代码比正常的直接数组大小检查运行速度慢约700倍。
The speed loss with debugging disabled is not very significant, though it is visible: code without exceptions is about 30% faster (for roughly 50% of false returns). The speed loss in debug mode is astonishing. The exception-based code runs about 700 times slower than the normal straight-up array size check.
例外背后的一般思想是允许一种处理 exceptiona 条件的方法。在这种情况下,根本没有异常条件 - 范围检查只是代码的正常部分。仅仅因为这个原因,在这种情况下不应该使用例外。
The general idea behind exceptions is to allow a way to handle exceptiona conditions. In this case, there is no exceptional condition at all - the range check is just a normal part of code. For that reason alone the exception should not be used in this situation.