我写了一个程序来测试try catch块是否影响运行时间。代码如下所示
public class ExceptionTest {
public static void main(String[] args) {
System.out.println("Loop\t\tNormal(nano second)\t\tException(nano second)");
int[] arr = new int[] { 1, 500, 2500, 12500, 62500, 312500, 16562500 };
for (int i = 0; i < arr.length; i++) {
System.out.println(arr[i] + "," + NormalCase(arr[i]) + ","
+ ExceptionCase(arr[i]));
}
}
public static long NormalCase(int times) {
long firstTime=System.nanoTime();
for (int i = 0; i < times; i++) {
int a = i + 1;
int b = 2;
a = a / b;
}
return System.nanoTime()-firstTime;
}
public static long ExceptionCase(int times) {
long firstTime =System.nanoTime();
for (int i = 0; i < times; i++) {
try {
int a = i + 1;
int b = 0;
a = a / b;
} catch (Exception ex) {
}
}
return System.nanoTime()-firstTime;
}
}
结果显示如下:
我想知道为什么转向 62500 和更大的数字的时间更少?它是否溢出?似乎没有。