views:

63

answers:

1

In Java we can do conditional compilation like so

private static final boolean DO_CHECK = false;

...

if (DO_CHECK) {
   // code here
}

The compiler will see that DO_CHECK is always false and remove the entire if-statement. However, sometimes, especially in library code, we can't use conditional compilation, but I'm wondering, can we use conditional JIT-compilation?

 private final boolean doCheck;

 public LibraryClass(boolean d) {
    doCheck = d;
 }


 public void oftenCalledMethod() {
     if (doCheck) {
       ...
     }
 }

If we construct LibraryClass with doCheck = false, will the JIT-compiler (in Hotspot) remove the if-statement as well?

Update: I just realised that JIT-compilation is most probably not done on instance level, so I think this wouldn't work, but maybe there's a static way?

A: 

JIT stands for "just in time". That means stuff is compiled just before the VM thinks it needs it. So depending on the level of atomicity of checking you might find the code that never gets run never gets JIT compiled anyway.

JeremyP
The code inside the if will not get compiled, but I'm wondering if the check itself (which may be expensive) is optimised away.
Bart van Heukelom
doing a comparison on a boolean? It's unlikely to be expensive.
JeremyP