Built-in string formatting vs string concatenation as logging parameter

霸气de小男生 提交于 2019-12-03 10:19:39

I believe you have your answer there.

Concatenation is calculated beforehand the condition check. So if you call your logging framework 10K times conditionally and all of them evaluates to false, you will be concatenating 10K times with no reason.

Also check this topic. And check Icaro's answer's comments.

Take a look to StringBuilder too.

Consider the below logging statement :

LOGGER.debug("Comparing objects: " + object1 + " and " + object2);

what is this 'debug' ?

This is the level of logging statement and not level of the LOGGER. See, there are 2 levels :

a) one of the logging statement (which is debug here) :

"Comparing objects: " + object1 + " and " + object2

b) One is level of the LOGGER. So, what is the level of LOGGER object : This also must be defined in the code or in some xml , else it takes level from it's ancestor .

Now why am I telling all this ?

Now the logging statement will be printed (or in more technical term send to its 'appender') if and only if :

Level of logging statement >= Level of LOGGER defined/obtained from somewhere in the code

Possible values of a Level can be

DEBUG < INFO <  WARN < ERROR

(There can be few more depending on logging framework)

Now lets come back to question :

"Comparing objects: " + object1 + " and " + object2

will always lead to creation of string even if we find that 'level rule' explained above fails.

However,

LOGGER.debug("Comparing objects: {} and {}",object1, object2);

will only result in string formation if 'level rule explained above' satisfies.

So which is more smarter ?

Consult this url.

String concatenation means LOGGER.info("The program started at " + new Date());

Built in formatting of logger means
LOGGER.info("The program started at {}", new Date());

very good article to understand the difference http://dba-presents.com/index.php/jvm/java/120-use-the-built-in-formatting-to-construct-this-argument

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!