3

I always see it is better to check whether log.isDebugEnabled before adding a log.debug statement.

I guess it should be taken care by the logging framework, could you please let me know what is the advantage of having this condition check?

Luiggi Mendoza
  • 85,076
  • 16
  • 154
  • 332
Adam
  • 727
  • 4
  • 11
  • 21

2 Answers2

1

Consider the following example:

if (log.isDebugEnabled()) {
    log.debug("This is my complicated object" + veryComplicatedObject.toString());
}

String concatenation may be expensive (memory-wise), and there is no reason to perform it if we aren't going to log it anyway. Checking the logging level beforehand saves constructing redundant strings.

Mureinik
  • 297,002
  • 52
  • 306
  • 350
  • Nice, example. Java has no lazy evaluation, so that's the way to go. – mike Sep 26 '13 at 21:21
  • If you're using Log4J 2 or SLF4J, placeholders in log messages can give you the performance benfits of the "is enabled" check without the verbosity: http://www.slf4j.org/faq.html#logging_performance – dnault Sep 26 '13 at 21:53
0

It optimization, doing a check simply saves cpu time in going to the class and checking to see if the level you want to report at is set or not. It only starts to make a different if you're using a lot of logging requests (tens of thousands or more) or multiple logging requests per section.

awm
  • 2,723
  • 2
  • 18
  • 26