Search code examples
javastringcoding-styleconcatenation

Java string concatenation efficiency


Is this bad ?

(imagine it's bigger)

int count;
//done something to count
String myString = "this " + "is " + "my " + "string" + "and " + this.methodCall() + " answer " + "is : " + count;

or is it better in a StringBuilder/StringBuffer?


Solution

  • Java compiler will convert it into StringBuilder to increase the performance of repeated string concatenation. http://java.sun.com/docs/books/jls/third%5Fedition/html/expressions.html#15.18.1.2

    Its when you are concatenating in a loop compiler can't substitute StringBuilder by itself that's when you should consider from concatenation to StringBuilder.