Java If(false) Compile
I am developing a dynamic web project using Tomcat. It is useful to have a global fl开发者_StackOverflow社区ag that is the only thing I have to change between my development and deployment servers. The biggest use of the flag is with print statements.
public class Debug {
public final static boolean DEVEL = true;
public static void print(String message){
if(DEVEL){
System.out.println(message);
}
}
}
My question is, will java compile out the print statements. i.e. if the devel tag is false, the messages will obviously not print but will they be included in the class files (devel is final). This is a question of efficiency. I've heard that the java compiler is very smart but will it pick up on this.
use the 'final' attribute (as you did), and it will compile out the code:
public static final boolean DEVEL = false;
You can check by grepping the resultant class file for a string that would appear only if the code were compiled.
Take a look into this article:
http://www.javaworld.com/javaworld/jw-03-2000/jw-03-javaperf_4.html
The code you presented is called a "dead code" so it will not be included in the compiled class file if you set DEVEL to false it will not be included in the bytecode.
Also, check the command
javap -c
to see the resulting bytecode of your class.
If you want to have the compiler not compile it out, use this:
public final static boolean DEVEL = Math.random() > -1;
The compiler won't know that this is always true
. (of course use < -1
for false
)
I find this trick handy when you want to remove code temporarily without having the compiler complain abut dead code, eg:
void myMethod() {
// temporarily exit early
if (Math.random() > -1) return;
// usual code
}
I have never seen the compiler remove code like this, however the JIT will effectively remove code which never runs. Assertions is a common use case for this. There may still be a notional cost but generally one not worth worrying about. i.e. less than 1 nano-second.
The cost can be greater if the toString() method of the message is costly. The toString method of a large sql query in a prepared statement caused a heap overflow due to this line. Thus the standard did not remove it.
精彩评论