try-catch和throws Exception在性能方面有什么区别? [英] What is the difference between try-catch and throws Exception in terms of performance?

查看:358
本文介绍了try-catch和throws Exception在性能方面有什么区别?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I know that there are difference in terms of usage. But I would like to discuss about the performance difference.

BTW,有效Java中有一句话:

BTW, there is a sentence in "Effective Java":


配售try-catch块中的代码禁止现代JVM实现可能执行的某些优化。

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

因此,如果有一个方法抛出异常,这是否意味着这种优化不适用于这种方法?

So, if there is a method throwing Exceptions, does it means that such kind of optimization won't be applied to this method?

推荐答案

从论文中,在存在例外的情况下优化Java程序


Java语言规范要求例外是准确的,
意味着:

The Java language specification requires that exceptions be precise, which implies that:


  1. 当抛出异常时,相应异常处理程序入口处的程序状态observable必须与原始程序的
    相同;和

  2. 例外必须按照原始(未优化)程序指定的顺序抛出。

为了满足精确的异常要求,Java编译器禁用
跨越可能抛出
异常的指令的许多重要优化...这妨碍了广泛的程序优化,例如
指令调度,指令选择,循环变换,
和并行化。

To satisfy the precise exception requirement, Java compilers disable many important optimizations across instructions that may throw an exception...This hampers a wide range of program optimizations such as instruction scheduling, instruction selection, loop transformations, and parallelization.

存在 try-catch 块,JVM维护一个异常表。对于每个新的catch块,编译器将向异常表添加一个条目。如果发生异常,JVM需要遍历表中的每个条目并检查异常表中是否定义了异常(这也需要进行类型分析)。结果是一个更复杂的控制结构,这反过来将极大地妨碍编译器优化。

In presence of a try-catch block, JVM maintains an exception table. For each new catch block, the compiler will add an entry to the exception table. If an exception occurs, JVM needs to go through each entry in the table and check if the exception is defined in the exception table (this requires type analysis too). The result is a much more complex control structure which in turn will greatly hamper compiler optimization.

抛出在另一个手,允许异常传播。虽然这对性能可能更好,但未捕获的异常可能会使线程,整个应用程序崩溃,甚至杀死JVM本身!

throws on the other hand, allows the exception to propagate. Although this might be better for performance, an uncaught exception can potentially crash the thread, the whole application, or even kill the JVM itself!

如何确定何时使用 try-catch

How to decide when to use try-catch?

我认为正确性和可靠性问题比表现在这里。但是,如果您只考虑了性能,那么此链接中的作者已经做了大量工作存在异常的java代码的基准标记。他们最基本的结论是,如果你使用异常来处理真正特殊情况(不是作为程序流控制的手段),那么性能就不会受到太大影响。

I think correctness and reliability concerns play a more important role than performance here. But if you have only performance in mind, the authors in this link have done extensive bench-marking for java code in presence of exceptions. Their most basic conclusion is that if you use exceptions for truly exceptional cases (not as a means for program flow control) there will not be much of a performance hit.

这篇关于try-catch和throws Exception在性能方面有什么区别?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆