Posts Tagged ‘precompilation’

Fast debugging statements

Monday, August 25th, 2008

While reading Code Complete 2nd Edition I ran into a chapter which covers defensive programming. Defensive programming includes debugging, but not to any price of course. We don’t want performance of the application to suffer from debugging statements, at least not in production fase. Debugging is mainly used during development.

Implementation (Java)

So how do we implement debugging so that it minimally affects performance? According to the log4j website :

Actual logging is also quite fast, ranging from 21 microseconds using the SimpleLayout, 37 microseconds using the TTCCLayout. The performance of the PatternLayout is almost as good as the dedicated layouts, except that it is much more flexible.

Pretty fast huh?

logger.debug("Number of products: " + order.getNumberOfProducts());

Now we move to our production environment, we’ve changed the logging level to ‘error’ (thus not displaying the debug level).

The log will not show the debug message, but we don’t want the debug statement to be executed even! It’s creating a string instance, adding a integer value to it… we just don’t want that. We change it to:

if(logger.isDebugEnabled()){
	logger.debug("Number of products: " + order.getNumberOfProducts());
}

According to the log4j website:

It costs about 5 nanoseconds to determine if a logging statement should be logged or not.

Just to put things into context, 20 microseconds is 20000 nanoseconds. The only drawback of this implementation is that the check performed in ‘isDebugEnabled’ is also performed in ‘debug’. But who cares? If you’re debugging, you’re obviously not interested in 5 nanoseconds performance win (at that moment).

If you don’t mind recompiling your code for different environments you can make it even faster…

class Debug {
	public static final boolean DEBUG = false;
}

//somewhere in a method
if(Debug.DEBUG){
	logger.debug("Number of products: " + order.getNumberOfProducts());
}

How this is faster? The Java compiler sees the code within the if-statement is unreachable and the code will be left out, and that’s of course even faster than 5 nanoseconds. If someone decides to decompile your code, the debug statements will be gone.

Implementation (C/C++)

The last solution is comparable to something called ‘precompilation’ in the C-language (C and C++). There it looks like this:

#define DEBUG

#ifdef DEBUG
print("Debugging in C++");
#endif

If DEBUG is not defined, the code within ‘ifdef’ will not pass the preprocessor, and therefore will not make it into the compiled code.