相关疑难解决方法(0)

Java try/catch性能,是否建议将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.
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 …
Run Code Online (Sandbox Code Playgroud)

java performance readability try-catch

33
推荐指数
2
解决办法
2万
查看次数

尝试Catch Performance Java

捕获异常而不是进行检查时,try-catch需要多长时间(以纳秒为单位)(假设消息具有HashMap类型的查找性能)?

    try {
        timestamp = message.getLongField( MessageField.TIMESTAMP );
    } catch (MissingDataException e) {
        //Not all messages contain this field
    }
Run Code Online (Sandbox Code Playgroud)

VS

if (message.contains(MessageField.TIMESTAMP))
    timestamp = message.getLongField( MessageField.TIMESTAMP );
Run Code Online (Sandbox Code Playgroud)

java performance try-catch

6
推荐指数
1
解决办法
7392
查看次数

标签 统计

java ×2

performance ×2

try-catch ×2

readability ×1