Today, I was going through some code and saw lots of debug logs in it. I remembered this statement from log4j documentation seeing the amount of debug statements in the code.

When logging is turned off entirely or just for a set of levels, the cost of a log request consists of a method invocation plus an integer comparison. On a 233 MHz Pentium II machine this cost is typically in the 5 to 50 nanosecond range.

However, the method invocation involves the “hidden” cost of parameter construction.

For example, for some logger cat, writing,

logger.debug(“Entry number: ” + i + ” is ” + String.valueOf(entry[i]));

incurs the cost of constructing the message parameter, i.e. converting both integer i and entry[i] to a String, and concatenating intermediate strings, regardless of whether the message will be logged or not. This cost of parameter construction can be quite high and it depends on the size of the parameters involved.

To avoid the parameter construction cost write:

if(logger.isDebugEnabled() {
logger.debug(“Entry number: ” + i + ” is ” + String.valueOf(entry[i]));

This will not incur the cost of parameter construction if debugging is disabled. On the other hand, if the logger is debug-enabled, it will incur twice the cost of evaluating whether the logger is enabled or not: once in debugEnabled and once in debug. This is an insignificant overhead because evaluating a logger takes about 1% of the time it takes to actually log.


Today, by chance, I happened to come across the instrumentation facility in Java 1.5. I did not know about this till today. Well, everyday you learn something new :). So what is this instrumentation? Straight from JavaDocs

This class provides services needed to instrument Java programming language code. Instrumentation is the addition of byte-codes to methods for the purpose of gathering data to be utilized by tools. Since the changes are purely additive, these tools do not modify application state or behavior. Examples of such benign tools include monitoring agents, profilers, coverage analyzers, and event loggers.

As soon as I grasped this, the first things that struck my mind was that this can be used to remove unnecessary log statements from code. Viola, I found that some one has already done that.