Is there a correct way to pass arguments in slf4j?

diya picture diya · Aug 18, 2011 · Viewed 38.2k times · Source

Im using slf4j for tracing the information. My code is

private static final Logger log = LoggerFactory.getLogger(ObjectTest.class);

log.trace("Time taken to store " + count
            + " objects of size " + size +  " is " + (time) + " msecs");

log.trace("Time taken to store {} objects of size {} is {} msecs",
        new Object[] { count, size, time });

log.trace("Time taken to store {} objects of size {} is {} msecs",
        count, size, time);

Which would be the preferred mechanism to log traces.

Answer

sbridges picture sbridges · Aug 18, 2011

3 is the best.

3 and 2 generate the same (or nearly the same) bytecode, but 3 is easier to type and is shorter, so 3 is better than 2.

If trace is not enabled, 1 must perform string concatenation ("Time taken to store " + count + ....) which is somewhat expensive, while 2 does the string concatenation only if trace is enabled, which is why 3 is better than 1.