Search code examples
javacompiler-optimizationjit

Does the java optimizer eliminate code whose result is not used unless an exception is thrown


Consider following code (java 8):

try
{
    // try to create an instance of CardExpirationDate
    AfCardExpirationDate.getInstance( anExpMonth, anExpYear);
    return true;    // expiration date is valid
}
catch ( IllegalArgumentException e )    
{
    // invalid expiration date
    return false;
}

The result of the call to AfCardExpirationDate.getInstanceis never used. We check here only if it throws an IllegalArgumentException or not.

Is this safe? Or could a compiletime or runtime code optimizer strip off such a call?


Solution

  • The compiler can't optimize this out. Plain and simple.

    The compiler can't know if that unsuspicious call to getInstance() doesn't have side effects. Beyond that, the compiler obviously does notice that your method has two return paths, and that therefore the try/catch matters.

    Beyond that, as a Java programmer you do not care about optimisation steps that happen between java source code and class file byte code.

    The JIT at runtime has profiling information, and when it finds that method is invoked so often that it is worth optimizing, it will compile it at runtime to machine code. Doing all the things that a compiler with contextual profile knowledge can possibly do.

    Finally: you are mis-using try/catch for validation purposes. That is simply bad practice (for example because of the associated runtime performance cost). When you are really serious about A) code quality and B) runtime performance then simply allow the complete validation to take place without relying on some code throwing up.