[JAVA] Item 63: Beware the performance of string concatenation

63. Watch out for character combination performance

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

Item 63: Beware the performance of string concatenation
[Note] Java: Measures the speed of string concatenation
[Java] Speed comparison of string concatenation
Various methods of the String class
I read the source of String
Item 57 Minimize the scope of local variables
Item 57: Minimize the scope of local variables
Item 72: Favor the use of standard exceptions
[Delete the first letter of the character string] Ruby
Item 44: Favor the use of standard functional interfaces
[Java] Get the length of the surrogate pair string
[Java] The confusing part of String and StringBuilder
Improve the performance of your Docker development environment
Count the number of occurrences of a string in Ruby
The world of clara-rules (2)
Judgment of the calendar
The world of clara-rules (4)
The world of clara-rules (1)
The world of clara-rules (3)
The world of clara-rules (5)
The idea of quicksort
The idea of jQuery
About truncation by the number of bytes of String on Android
Put the file in the properties of string in spring xml configuration
The nth and n + 1st characters of a Ruby string
[Java] Try editing the elements of the Json string using the library