1

I saw this question and some similar and I think it's not duplicate :

StringBuilder vs String concatenation in toString() in Java

Here is the deal, I hear a very clever work colleague of mine talking this morning about how java optimizes up to 8 or 16 string concatenation(I'm not sure at this point) to string builder. Because this might have been a vague description of what I mean here is an example of 6 String concatenation :

public String test(){
     return "a" + "b" + "c" + "d" + "e" + "f";
}

So that this is actually translated to :

public String test(){
     StringBuilder sb = new StringBuilder();
     return sb.append("a").append("b").append("c").append("d").append("e").append("f").toString();
}

I had to leave the conversation earlier, is this true?If yes can someone provide more details of exact number up to when this optimization is done 8/16 or x?

I didn't know about this before I've heard it. good to know if true.

Community
  • 1
  • 1
ant
  • 22,634
  • 36
  • 132
  • 182
  • 3
    You can find a thorough explanation of how string concatenation works in Java in this blog post: http://www.znetdevelopment.com/blogs/2009/04/06/java-string-concatenation/ – Rens Verhage May 07 '12 at 11:29
  • @verhage can you please respond with an answer I'll accept your answer – ant May 07 '12 at 12:05

2 Answers2

3

As per request, here my comment as answer to the question:

You can find a thorough explanation of how string concatenation works in Java in this blog post: http://znetdevelopment.com/blogs/2009/04/06/java-string-concatenation

Matteo
  • 14,696
  • 9
  • 68
  • 106
Rens Verhage
  • 5,688
  • 4
  • 33
  • 51
1

I don't know about the exact number but generally you shouldn't worry about concatenating strings with the + operator, unless if the concatenation happens in the iteration of some loop, because that's the case where the compiler cannot optimize and you need to use StringBuilder explicitly, or even String.concat.

Which way is fastest depends also on whether your data is constant or variable. In your example the string would be concatenated at compile time to "abcdef".

alexg
  • 3,015
  • 3
  • 23
  • 36