I have often heard people saying that its one of the best practices to avoid String Concatenation
and use {}
instead while logging.
I was
The benefit of format strings in logging systems is, that the logging system can decide if the string concatenation must happen or not.
Let's use these lines as example:
log.debug("Count: " + list.size());
log.debug("Count: {}", list.size());
As long as the level for this logger is debug or below, there is no difference in performance, but if the log level is higher than debug the second line won't perform the concatenation at all.
Some of the answers to this question explain:
The short version is that format-based usage faster because in
Logger.debug("my name is {}", name);
the expensive string bashing only occurs after log4j decides that the event needs to be logged; e.g. after the filtering based on the logging level, etcetera.
By contrast, with the string concatenation version
Logger.debug("my name is " + name);
the string bashing happens while evaluating the arguments. Thus, it happens even in the cases where no event is actually logged. (You can partially avoid that with guards in your code, but it makes the logging code verbose.)
But take a look at this example:
log.debug("Count: " + list.size());
log.debug("Count: {}", list.size());
The format version will be faster, but both versions always evaluate the list.size()
expression. If that is an expensive operation, then you may need to resort to using a guard; e.g.
if (log.isDebugEnabled()) {
log.debug("Count: " + list.size());
}