Search code examples
javastringperformanceconcatenationstringbuilder

String Concatenation and then append in a loop


Found this excerpt from the book "Thinking in Java" written by Bruce Eckel.

If you try to take shortcuts and do something like append(a + ": " + c) , the compiler will jump in and start making more StringBuilder objects again.

Does that mean that we shouldn't replace a group of append operations with a single line of code; e.g result.append(i + ": " + 2*i + " ")?

StringBuilder result = new StringBuilder();
for(int i = 0; i < 25; i++) {
    result.append(i);
    result.append(": ");
    result.append(2*i);
    result.append(", ") 
}

Does the above statement hold true for Java 8 as well?

Excerpt from this answer on SO: (confused me even more)

At the point where you're concatenating in a loop - that's usually when the compiler can't substitute StringBuilder by itself.

Any aspect related to preferred coding style is also welcome.


Solution

  • This is not an optimisation the compiler will do for you efficiently. Stylistically, I would write it like this.

    StringBuilder result = new StringBuilder();
    for (int i = 0; i < 25; i++) {
        result.append(i).append(": ").append(2 * i).append(", ");
    }
    

    NOTE: IDEs, like IntelliJ, will detect and provide an auto-fix for this as it's a common translation.