Item 51 - Beware the performance of string concatenation

From Effective Java 2/e by Joshua Bloch

Strings are immutable
Using the string concatenation operator repeatedly to concatenate n strings requires time quadratic in n.

User StringBuilder instead of String it self

// Inappropriate use of string concatenation - Performs horribly!
public String statement() {
   String result = "";
   for (int i = 0; i < numItems(); i++)
      result += lineForItem(i);  // String concatenation
   return result;
}

public String statement() {
   StringBuilder b = new StringBuilder(numItems() * LINE_WIDTH);
   for (int i = 0; i < numItems(); i++)
      b.append(lineForItem(i));
   return b.toString();
}

Because the first method is quadratic in the number of items and the second is linear, the performance difference is even more dramatic for larger numbers of items.

Posted by The Finest Artist