0

I'm a Java newbie (started seriously learning 1-2 months ago). I've read that string concatenation often has terrible performance in Java, and that if you need to repeatedly concatenate a string, it's better to use a StringBuilder. But are there some cases where ordinary string concatenation is OK?

I'm particularly thinking of cases like:

String url = "http://example.com/"+ path + "?param1=" + param1 + "&param2=" 
       + param2 + "&param3=" + param3;

There are two things that I think might be true of cases like this:

  1. Java will go through successively producing the strings "http://example.com/about", "http://example.com/about/?param1=", etc., but doing so isn't so bad unless performance is really at a premium because you're only doing this ~a half-dozen times (whereas doing it a thousand times would be bad).
  2. Java is smart enough to not do the thing described in (1), and just makes one big string directly, because this code is all on one line. Therefore using StringBuilder here is totally unnecessary even if performance is at a premium.

Which is true?

  • If you are building a string all in one line, it's fine. The compiler might change it to a `StringBuilder` anyway. If you are building a string over lots of lines, particularly in a loop, it might be better to use a `StringBuilder`. – khelwood Jul 13 '15 at 17:58
  • This kind of chained `+` operator is litterally translated to `new StringBuilder(..).append(..).append(..).toString()` in the bytecode. So it is perfectly equivalent. However, if you use multiple assignments with `+` on the right-hand side, each assignment will use a new `StringBuilder` under the hood, which is bad for your perf, especially in terms of memory. – Joffrey Jul 13 '15 at 18:02

0 Answers0