String concatenation performance in Log4j

后端 未结 2 1800
一个人的身影
一个人的身影 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: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());
       }
    

提交回复
热议问题