我正在使用以下代碼來測試try塊的速度。令我驚訝的是,try塊使其更快。爲什麼?爲什麼添加一個try塊會使程序更快?
public class Test {
int value;
public int getValue() {
return value;
}
public void reset() {
value = 0;
}
// Calculates without exception
public void method1(int i) {
value = ((value + i)/i) << 1;
// Will never be true
if ((i & 0xFFFFFFF) == 1000000000) {
System.out.println("You'll never see this!");
}
}
public static void main(String[] args) {
int i;
long l;
Test t = new Test();
l = System.currentTimeMillis();
t.reset();
for (i = 1; i < 100000000; i++) {
t.method1(i);
}
l = System.currentTimeMillis() - l;
System.out.println("method1 took " + l + " ms, result was "
+ t.getValue());
// using a try block
l = System.currentTimeMillis();
t.reset();
for (i = 1; i < 100000000; i++) {
try {
t.method1(i);
} catch (Exception e) {
}
}
l = System.currentTimeMillis() - l;
System.out.println("method1 with try block took " + l + " ms, result was "
+ t.getValue());
}
}
我的機器正在運行64位Windows 7和64位JDK7。我得到了以下結果:
method1 took 914 ms, result was 2
method1 with try block took 789 ms, result was 2
而且我已經運行的代碼很多次,每一次我得到了幾乎相同的結果。
更新:
這裏是運行測試在MacBook Pro上十倍的結果,爪哇6的try-catch使得該方法更快,相同的窗口。
method1 took 895 ms, result was 2
method1 with try block took 783 ms, result was 2
--------------------------------------------------
method1 took 943 ms, result was 2
method1 with try block took 803 ms, result was 2
--------------------------------------------------
method1 took 867 ms, result was 2
method1 with try block took 745 ms, result was 2
--------------------------------------------------
method1 took 856 ms, result was 2
method1 with try block took 744 ms, result was 2
--------------------------------------------------
method1 took 862 ms, result was 2
method1 with try block took 744 ms, result was 2
--------------------------------------------------
method1 took 859 ms, result was 2
method1 with try block took 765 ms, result was 2
--------------------------------------------------
method1 took 937 ms, result was 2
method1 with try block took 767 ms, result was 2
--------------------------------------------------
method1 took 861 ms, result was 2
method1 with try block took 744 ms, result was 2
--------------------------------------------------
method1 took 858 ms, result was 2
method1 with try block took 744 ms, result was 2
--------------------------------------------------
method1 took 858 ms, result was 2
method1 with try block took 749 ms, result was 2
這是出問題的範圍,但您應該使用'System.nanoTime'來比較數據。閱讀[System.currentTimeMillis vs System.nanoTime](http://stackoverflow.com/q/351565/1065197)。 –
@RahulAgrawal我交換了代碼並得到了相同的結果。 –
我對OP的代碼做了很多測試,我確認了他的發現。 –