Rule 7:Beware the performance of string concatenation
Using the string concatenation operator repeatedly to concatenate n strings requires time quadratic in n. This is an unfortunate consequence of the fact that strings are immutable.
// Inappropriate use of string concatenation – Performs poorly!
public String statement() {
String result = “”;
for (int i = 0; i < numItems(); i++)
result += lineForItem(i); // String concatenation
return result;
}
To achieve acceptable performance, use a StringBuilder in place of a String to store the statement under construction:
public String statement() {
StringBuilder b = new StringBuilder(numItems() * LINE_WIDTH);
for (int i = 0; i < numItems(); i++)
b.append(lineForItem(i));
return b.toString();
}
the second method runs 6.5 times faster than the first on my machine. Because the first method is quadratic in the number of items and the second is linear