In what ways can putting some code in try catch blocks prevent the JVM from doing optimization?

StackOverflow https://stackoverflow.com/questions/11557766

  •  21-06-2021
  •  | 
  •  

Question

From Exceptions chapter in Effective Java:

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

Why and how does a try-catch block prevent optimization by JVMs ?

Was it helpful?

Solution

One of the reasons "why" is that exceptions and exception handling are assumed to be exceptional; i.e. code that is rarely executed. It follows that time spent by the JIT compiler on optimizing exception handlers is going to have little benefit to the overall performance.

The JIT compiler's optimizer has to balance the performance benefits of optimizations that are effective against the costs of optimizing. The latter include:

  • the cost of checking complicated preconditions to see if an optimization is possible,
  • the cost of doing the actual optimization, and
  • the cost (to Oracle) of implementing and maintaining a complex piece of software that does an optimization that is (under normal conditions / assumptions) not going to be effective.

There may also be technical reasons that inhibit optimization of exception handlers. For instance, it may not be easy (or even possible) for the optimizer to figure out where the flow of control "came from". Hence, optimization that are based on knowing that (e.g. caching stuff in registers, hoisting common subexpressions, ...) can't be performed.

OTHER TIPS

The JVM might not combine or re-order operations inside the try/catch block with those outside the try/catch block. Every layer of complexity makes optimisation harder. If its a relatively rare case, it might not be handled by the JVM which will, if in doubt, choose correctness rather than optimal code.

Check the following link:

How slow are Java exceptions?

I guess exceptions are Java objects and these objects need to be created. Creating an object is a costly operation. So use exceptions only for handling errors and not to control flow.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top