0

As is well known

LOGGER.debug("The parameter p1 cannot be " + p1 +
        ", it must be between " + P1_MIN + " and " + P1_MAX);

Has the disadvantage that string concatenation is done even if the result will be discarded due to logger settings. To avoid this, the following boilerplate is popular

if (LOGGER.isDebugEnabled())
{
    LOGGER.debug("The parameter p1 cannot be " + p1 +
            ", it must be between " + P1_MIN + " and " + P1_MAX);
}

Which avoids it at the cost of three extra lines.

slf4j (and others) offer an alternative using varargs (and overloading):

    LOGGER.debug("The parameter p1 cannot be {} , it must be between {} and {}", 
             p1, P1_MIN, P1_MAX);

This looks much cleaner but there is an Object array getting created to pass variable number of parameters.

How expensive is this object array creation? Does its cost outweigh the advantage of reducing lines of code?

I suspect the varargs/formatter based methods are created exactly to address the above boilerplate so even though slightly subjective replies from experts will help great many numbers of programmers. Also, IMHO it is not subjective if object array creation is either very cheap (which is my hope) or very expensive.

Miserable Variable
  • 27,834
  • 15
  • 70
  • 128
  • It's not just the creation and population of the `Object[]` The `slf4j` alternative is also internally going to have to parse the format string, create a formatter object, and build up the formatted string. It's not clear to me why you would expect that would be less expensive than just testing whether or not the logger has debug enabled. – QuantumMechanic May 10 '12 at 17:53
  • On varargs performance: http://stackoverflow.com/questions/2426455/javas-varargs-performance – Konstantin V. Salikhov May 10 '12 at 17:55
  • @QuantumMechanic good point, but lets say we ignore the comparative costs of creating the formatted output string and concatenating them – Miserable Variable May 10 '12 at 17:55
  • @KonstantinV.Salikhov according to that question `varargs` is very expensive. I am reading that right? – Miserable Variable May 10 '12 at 17:57
  • @MiserableVariable at least in 2010 - yes. How expensive it is nowadays - I don't know. – Konstantin V. Salikhov May 10 '12 at 18:02
  • it's not expensive until you're running at an extreme scale. I highly recommend this presentation from Twitter guys. They care about their objects' memory footprint! http://www.infoq.com/presentations/JVM-Performance-Tuning-twitter – Pavel Veller May 10 '12 at 18:15
  • SFL4J does not use vargs/Object[]. It offers overloaded methods for 1 and 2 arguments, and an overloaded method with Object[] as last parameter for dealing with 3 or more arguments. – Ceki May 11 '12 at 05:35
  • @Ceki oops...thanks. I was looking at `void debug(String format, Object[] argArray)` and reading `void debug(String format, Object... argArray)`. – Miserable Variable May 11 '12 at 15:52

0 Answers0