Dar*_*usz 5 java exception indexoutofboundsexception range-checking
我想检查给定的坐标是否与数组有关.
public boolean checkBounds(int x, int y) {
try {
Object val = array[x][y];
return true;
} catch (ArrayIndexOutOfBoundsException e) {
return false;
}
}
Run Code Online (Sandbox Code Playgroud)
我能这样做吗?这是一种有效的方法吗?
Dar*_*usz 12
使用异常处理诸如空检查,边界检查,文件存在检查等操作时,每当抛出异常时都会引入大量开销.
如果您只是检查边界,您会做什么:
使用基于异常的检查时您实际在做什么:
通过这个简单的测试程序,我测量了两种类型的阵列边界检查的速度.
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);
}
}
Run Code Online (Sandbox Code Playgroud)
结果:
JDK 7,eclipse Run as模式:
time check=[911620628]
exc=[1192569638]
diff=[280949010] percent diff=[30.818632375220886]
Run Code Online (Sandbox Code Playgroud)
JDK 7,eclipse Debug模式:
time check=[931243924]
exc=[651480777121]
diff=[650549533197] percent diff=[69858.12378809143]
Run Code Online (Sandbox Code Playgroud)
禁用调试时的速度损失不是很显着,尽管它是可见的:没有例外的代码快30%(大约50%的错误返回).调试模式下的速度损失是惊人的.基于异常的代码运行速度比正常的直接数组大小检查慢约700倍.
异常背后的一般思想是允许一种处理异常条件的方法.在这种情况下,根本没有异常条件 - 范围检查只是代码的正常部分.仅仅因为这个原因,不应该在这种情况下使用例外.