gpt4 book ai didi

java - try-catch 和 throws Exception 在性能上有什么区别?

转载 作者:行者123 更新时间:2023-11-29 04:22:54 26 4
gpt4 key购买 nike

我知道在用法方面存在差异。但我想讨论性能差异。

BTW,《Effective Java》里面有一句话:

Placing code inside a try-catch block inhibits certain optimizations that modern JVM implementations might otherwise perform.

那么,如果有一个方法抛出异常,是否意味着这种优化不会应用到这个方法上?

最佳答案

为什么不在代码中尝试?

public class ExPerformanceTest {

private int someVar = 0;
private int iterations = 100000000;

@Test
public void throwTest() throws Exception {
long t;
t = System.currentTimeMillis();
for (int i = 0; i < iterations; i++) {
throwingMethod();
}
t = System.currentTimeMillis() - t;
System.out.println("Throw Test took " + t + " ms");
}

@Test
public void tryCatchTest() throws Exception {
long t;
t = System.currentTimeMillis();
for (int i = 0; i < iterations; i++) {
tryCatchMethod();
}
t = System.currentTimeMillis() - t;
System.out.println("Try-Catch Test took " + t + " ms");
}

@Test
public void anotherTryCatchTest() throws Exception {
long t;
t = System.currentTimeMillis();
for (int i = 0; i < iterations; i++) {
tryCatchMethodThatNeverEverThrows();
}
t = System.currentTimeMillis() - t;
System.out.println("Try-Catch That Never Throws Test took " + t + " ms");
}

private void throwingMethod() throws Exception {
// do some stuff here
someVar++;
willNeverThrow();
}

private void tryCatchMethod() {
try {
// do some stuff here
someVar++;
willNeverThrow();
} catch (Exception e) {
System.out.println("You shouldn't see this ever");
}
}

private void tryCatchMethodThatNeverEverThrows() {
try {
// do some stuff here
someVar++;
} catch (Exception e) {
System.out.println("You shouldn't see this ever");
}
}

private void willNeverThrow() throws Exception {
if (someVar == -1) {
throw new RuntimeException("Shouldn't happen");
}
}
}

这给出了相当预期的数字:

运行 1

Try-Catch That Never Throws Test took 36 ms
Throw Test took 139 ms
Try-Catch Test took 160 ms

运行 2

Try-Catch That Never Throws Test took 26 ms
Throw Test took 109 ms
Try-Catch Test took 113 ms

运行 3

Try-Catch That Never Throws Test took 32 ms
Throw Test took 137 ms
Try-Catch Test took 194 ms

显然,JVM 发现 tryCatchMethodThatNeverEverThrows 实际上不需要 catch 部分并对其进行了优化,因此方法执行时间比其他方法少几倍。

在其他情况下,使用 catch 子句进行处理确实需要一些时间。

关于java - try-catch 和 throws Exception 在性能上有什么区别?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48001706/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com