Video in progress
What is the benefit of using a `{}` placeholder in a log message instead of joining strings with `+`?
With a placeholder, the message is built only if that level is enabled, so no needless String is created for disabled DEBUG logs. The code is also easier to read.
📖 Answer
// bad: the string is built even when DEBUG is off, toString() is called
log.debug("Order: " + order + ", items: " + items);
// good: the level is checked first, then it is formatted
log.debug("Order: {}, items: {}", order, items);
In the first version Java builds the whole string first, and then inside debug() throws it away because "DEBUG is off". If order.toString() is heavy or this code is called thousands of times a second, you put a pointless load on the CPU and GC.
There is one nuance: a placeholder doesn't save you from evaluating the arguments. In log.debug("{}", buildHugeReport()), buildHugeReport() is called anyway. In that case you need if (log.isDebugEnabled()) or the lambda API in SLF4J 2.
If the last argument is a Throwable, SLF4J doesn't put it into a placeholder, it prints it as a stack trace.
Sign up to mark studied questions and save your progress.