我知道在使用方面存在差异。但我想讨论一下性能差异。
顺便说一句,《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/