问题:Java中的异常处理真的很慢吗?
传统观点,以及许多谷歌搜索结果都认为,Java中的正常程序流不应该使用异常逻辑.通常会给出两个原因,
- 它真的很慢——甚至比常规代码慢一个数量级(给出的原因各不相同),
和
- it is messy because people expect only errors to be h和led in exceptional code.
这个问题是关于#1的.
As an example, this page describes Java exception h和ling as "very slow" 和 relates the slowness to the creation of the exception message string - "this string is then used in creating the exception object that is thrown. This is not fast." The article Effective Exception H和ling in Java says that "the reason for this is due to the object creation aspect of exception h和ling, which thereby makes throwing exceptions inherently slow". Another reason out there is that the stack trace generation is what slows it down.
My testing (using Java 1.6.0_07, Java HotSpot 10.0, on 32 bit Linux), indicates that exception h和ling is no slower than regular code. I tried running a method in a loop that executes some code. At the end of the method, I use a boolean to indicate whether to return or throw. This way the actual processing is the same. I tried running the methods in different orders 和 averaging my test times, thinking it may have been the JVM warming up. In all my tests, the throw was at least as fast as the return, if not faster (up to 3.1% faster). I am completely open to the possibility that my tests were wrong, but I haven't seen anything out there in the way of the code sample, test comparisons, or results in the last year or two that show exception h和ling in Java to actually be slow.
bootstrap 我走上这条道路的是我需要使用的API,它将异常作为正常控制逻辑的一部分抛出.我想纠正它们的用法,但现在我可能无法纠正.我会不得不称赞他们的前瞻性思维吗?
In the paper Efficient Java exception h和ling in just-in-time compilation, the authors suggest that the presence of exception h和lers alone, even if no exceptions are thrown, is enough to prevent the JIT compiler from optimizing the code properly, thus slowing it down. I haven't tested this theory yet.