【发布时间】:2012-10-02 22:25:02
【问题描述】:
我正在使用以下代码来测试 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、Java 6 上运行测试十次的结果。Try-catch 使该方法更快,与在 Windows 上相同。
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。 -
@RahulAgrawal 我交换了代码并得到了相同的结果。
-
我围绕 OP 的代码做了很多测试,我证实了他的发现。
-
是的:添加一个try catch,即使是完全不相关的错误或异常,确实可以使代码更快。如果你在 catch 中重新抛出异常,它并不会让它更快。
-
您好,请查看stackoverflow.com/questions/8423789/…,它将引导您访问 IBM 公司的论文:ibm.com/developerworks/java/library/j-benchmark1/index.html,它将向您展示如何执行正确的 java 代码基准测试。
标签: java performance exception try-catch