If you want to combine a lot of characters, use StringBuilder instead of using the + operator. Since String is immutable, a new object is created every time a character is combined.
Below is an example of character combination using String.
// 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;
}
The following is the case when using StringBuilder.
public String statement() {
StringBuilder b = new StringBuilder(numItems() * LINE_WIDTH);
for (int i = 0; i < numItems(); i++)
b.append(lineForItem(i));
return b.toString();
}
Recommended Posts