Tip of the day: AVOID String concatenation in Loggers

940 views
Skip to first unread message

Andrea Arcuri

unread,
Oct 20, 2015, 11:57:40 AM10/20/15
to EvoSuite
writing something like:

logger.debug("this is not "+ foo + " very " + bar +" efficient");

is not efficient, as most of the time debug logs are deactivated, and concatenating strings is
expensive. Recall String is immutable, and each "+" create a new String object.
The above logging can be rewritten into:

logger.debug("this is not {} very {} efficient", foo, bar);

Note: not a big deal for "warn"/"error", as those are/should be rare... but it can become
quite an overhead for trace/debug/info

Jose Campos

unread,
Oct 21, 2015, 10:24:45 AM10/21/15
to EvoSuite


On Tuesday, 20 October 2015 16:57:40 UTC+1, Andrea Arcuri wrote:
writing something like:

logger.debug("this is not "+ foo + " very " + bar +" efficient");

is not efficient, as most of the time debug logs are deactivated, and concatenating strings is
expensive. Recall String is immutable, and each "+" create a new String object.

yes. when I was doing my master thesis, my Java code was significantly slow just
because of concatenating strings. since then, I've been using (almost always :-) ) StringBuilder.

Rene Just

unread,
Oct 21, 2015, 3:08:47 PM10/21/15
to EvoSuite
Just a minor comment, the Java compiler (at least OpenJDK and Oracle javac) actually does that for you: it applies constant folding, and it replaces other String concatenations with a StringBuilder. You can think of String concatenation as syntactic sugar.
So, I think that using a trivial String concatenation is fine because it is easier to read and faster to type. I agree, however, that one should keep this problem in mind, in particular when building Strings in loops.

Andrea Arcuri

unread,
Oct 21, 2015, 4:55:39 PM10/21/15
to EvoSuite


On Wednesday, 21 October 2015 21:08:47 UTC+2, Rene Just wrote:
Just a minor comment, the Java compiler (at least OpenJDK and Oracle javac) actually does that for you: it applies constant folding, and it replaces other String concatenations with a StringBuilder.

interesting, i did not know about it... :)

btw, still, even if it is replaced by StringBuilder, it gives an unnecessary overhead in "logger.debug(...)" when we have default logging level (ie WARN)
Reply all
Reply to author
Forward
0 new messages