Java try/catch性能,是否建议将try子句中的内容保持在最低限度?

Osc*_*mez 33 java performance readability try-catch

考虑到你有这样的代码:

doSomething() // this method may throw a checked a exception
//do some assignements calculations
doAnotherThing() //this method may also throw the same type of checked exception
//more calls to methods and calculations, all throwing the same kind of exceptions.
Run Code Online (Sandbox Code Playgroud)

现在我知道,实际上在构造异常时会出现性能损失,特别是展开堆栈.我还阅读了几篇文章,指出在输入try/catch块时会有轻微的性能损失,但这些文章似乎都没有结论.

我的问题是,是否建议将try catch中的行保持最小?,即只在try子句中包含可以实际抛出正在捕获的异常的行.try子句中的代码运行速度较慢或导致性能下降吗?

但考虑到这一点,更重要的是最佳实践/更易读的解决方案:

try {
    doSomething() // this method may throw a checked a exception
//do some assignements calculations
doAnotherThing() //this method may also throw the same type of checked exception
//more calls to methods and calculations, all throwing the same kind of exceptions.
}
catch (MyCheckedException e) {
   //handle it
}
Run Code Online (Sandbox Code Playgroud)

要么 :

try {
    doSomething() // this method may throw a checked a exception
}
catch (MyCheckedException e) {
   //Store my exception in a Map (this is all running in a loop and I want it to   continue running, but I also want to know which loops didn't complete and why)
   continue;     
} 
 //do some assignements calculations
try {
    doAnotherThing() // this method may throw a checked a exception
}
catch (MyCheckedException e) {
    //Store my exception in a Map (this is all running in a loop and I want it to   continue running, but I also want to know which loops didn't complete and why)
   continue;
} 
Run Code Online (Sandbox Code Playgroud)

这是考虑到您将以完全相同的方式处理所有这些已检查的异常.

use*_*421 23

是否建议将try catch中的线条保持最小?

不能.无法想象你怎么能认为一个try区块或任何区块的长度会对性能产生任何影响.

try子句中的代码运行速度较慢或导致性能下降吗?

没有.

正如您所观察到的,异常只会在抛出时产生性能成本.

如果您担心"尝试"性能,那么要做的就是将代码保持在最大值?

  • 这些激进的编辑有什么用?如果你不知道如何期待Java的try-catch被实现,那么关注你是一件非常合理的事情.可能有一些角落案例使得JIT难以为所有提问者所知道的"尝试"代码.JavaScript虚拟机在任何地方都有这样的陷阱. (2认同)

rwa*_*wat 15

在这里的示例中,真正的性能影响是doSomething()和doAnotherThing()都抛出异常.输入try-block很快,直到它抛出异常.

这真的取决于你的情况.如果你在任何方式抛出MyCheckedException时都需要做同样的事情,我认为将它们放在同一个try块中更具可读性和更高性能,但如果你需要以不同的方式处理两种不同的情况,那么当然将它们分开更有意义.

编辑:我读了评论的结尾,你假设处理方式相同,在这种情况下,我将它们放在同一个试块中.