【发布时间】:2013-09-02 07:41:01
【问题描述】:
我写了一个程序来测试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 和更大的数字的时间更少?它是否溢出?似乎没有。
【问题讨论】:
-
相关:stackoverflow.com/q/504103/1065197,注意规则1到4。
-
为了快速改进,请在您现在所做的所有事情周围添加一个外循环,它将整个测试重复至少 10 次。您还可以使用无限循环并在看到数字稳定时手动终止。