Logger slf4j advantages of formatting with {} instead of string concatenation

Hernán Eche picture Hernán Eche · May 11, 2012 · Viewed 105.2k times · Source

Is there any advantage of using {} instead of string concatenation?

An example from slf4j

logger.debug("Temperature set to {}. Old temperature was {}.", t, oldT);

instead of

logger.debug("Temperature set to"+ t + ". Old temperature was " + oldT);

I think it's about speed optimization because parameters evaluation (and string concatenation) could be avoided in runtime depending on a config file. But only two parameters are possible, then sometimes there is no other choice than string concatenation. Needing views on this issue.

Answer

skaffman picture skaffman · May 11, 2012

It is about string concatenation performance. It's potentially significant if your have dense logging statements.

(Prior to SLF4J 1.7) But only two parameters are possible

Because the vast majority of logging statements have 2 or fewer parameters, so SLF4J API up to version 1.6 covers (only) the majority of use cases. The API designers have provided overloaded methods with varargs parameters since API version 1.7.

For those cases where you need more than 2 and you're stuck with pre-1.7 SLF4J, then just use either string concatenation or new Object[] { param1, param2, param3, ... }. There should be few enough of them that the performance is not as important.