Dead-code elimination: Java Logging
In my previous article, we have seen how the Java compiler (javac), inlines final declared variables as a compile-time optimisation.
Today, we are going to focus in dead-code elimination. Dead-code elimination is the process, where the compiler removes part of code that will never be executed.
Java logging: a simple use case
Let's say that we need to build a simple logging facility for our Java program and the requirements indicate to have the classic interface of methods; info and debug.
The tricky part with the logging, is that usually it is some kind of string, serialized. The anti-pattern that happens all the time, is that the string message is usually evaluated, even if the logging level ignores it in the end.
So, this is the Logging class:
public class Logger {
private final static Logger defaultInstance;
private final static boolean debugMode = true;
static {
defaultInstance = new Logger();
}
private Logger() {
// empty
}
public void info(String fmt, Object ... args) {
System.out.printf(fmt, args);
}
public void debug(String fmt, Object ... args) {
if (debugMode) {
System.out.printf(fmt, args);
}
}
public static Logger…