String concatenation performance in Log4j

后端 未结 2 1799
一个人的身影
一个人的身影 2021-01-18 22:54

I have often heard people saying that its one of the best practices to avoid String Concatenation and use {} instead while logging.

I was

相关标签:
2条回答
  • 2021-01-18 23:23

    The benefit of format strings in logging systems is, that the logging system can decide if the string concatenation must happen or not.

    Let's use these lines as example:

    log.debug("Count: " + list.size());
    log.debug("Count: {}", list.size());
    

    As long as the level for this logger is debug or below, there is no difference in performance, but if the log level is higher than debug the second line won't perform the concatenation at all.

    0 讨论(0)
  • 2021-01-18 23:32

    Some of the answers to this question explain:

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

    The short version is that format-based usage faster because in

       Logger.debug("my name is {}", name);
    

    the expensive string bashing only occurs after log4j decides that the event needs to be logged; e.g. after the filtering based on the logging level, etcetera.

    By contrast, with the string concatenation version

       Logger.debug("my name is " + name);
    

    the string bashing happens while evaluating the arguments. Thus, it happens even in the cases where no event is actually logged. (You can partially avoid that with guards in your code, but it makes the logging code verbose.)


    But take a look at this example:

       log.debug("Count: " + list.size());
       log.debug("Count: {}", list.size());
    

    The format version will be faster, but both versions always evaluate the list.size() expression. If that is an expensive operation, then you may need to resort to using a guard; e.g.

       if (log.isDebugEnabled()) {
           log.debug("Count: " + list.size());
       }
    
    0 讨论(0)
提交回复
热议问题