In log4j, does checking isDebugEnabled before logging improve performance?
Since in option 1 the message string is a constant, there is absolutely no gain in wrapping the logging statement with a condition, on the contrary, if the log statement is debug enabled, you will be evaluating twice, once in the isDebugEnabled()
method and once in debug()
method. The cost of invoking isDebugEnabled()
is in the order of 5 to 30 nanoseconds which should be negligible for most practical purposes. Thus, option 2 is not desirable because it pollutes your code and provides no other gain.
In this particular case, Option 1 is better.
The guard statement (checking isDebugEnabled()
) is there to prevent potentially expensive computation of the log message when it involves invocation of the toString()
methods of various objects and concatenating the results.
In the given example, the log message is a constant string, so letting the logger discard it is just as efficient as checking whether the logger is enabled, and it lowers the complexity of the code because there are fewer branches.
Better yet is to use a more up-to-date logging framework where the log statements take a format specification and a list of arguments to be substituted by the logger—but "lazily," only if the logger is enabled. This is the approach taken by slf4j.
See my answer to a related question for more information, and an example of doing something like this with log4j.