Sub topic 2
The Cost of Concatenating in a Loop
Prerequisites and the Working Model
This chapter assumes you know basic Java variables, loops, methods, and the String class. You should also know that a String is an object, while an int is a primitive value.
A Java String is immutable. Immutable means that an object cannot change after it is created. Operations that appear to modify a string actually create another String object.
For example:
String word = "cat";
word = word + "s";
System.out.println(word); // catsThe original "cat" object remains unchanged. Java creates a new string containing "cats" and stores a reference to that new object in word.
The assignment makes this easy to overlook. The variable changes what it refers to, but the original object does not change.
What `+=` Does in a Loop
Consider this program:
public class Main {
public static void main(String[] args) {
String s = "";
for (int i = 0; i < 5; i++) {
s += i;
}
System.out.println(s); // 01234
}
}Each s += i operation must produce a new string. On each iteration, Java must copy the characters already in s, convert i to text, and add the new characters.
The work grows as the string grows:
| Iteration | Existing characters copied | New result |
|---|---|---|
| 1 | 0 | `0` |
| 2 | 1 | `01` |
| 3 | 2 | `012` |
| 4 | 3 | `0123` |
| 5 | 4 | `01234` |
For a loop that runs n times, the total copied text can be approximately:
0 + 1 + 2 + ... + (n - 1)
That sum grows roughly as n², called quadratic growth. The exact cost also depends on the lengths of the values being added, but the pattern is the same: later iterations copy more text than earlier iterations.
Why This Creates Extra Work
The following diagram shows the references after several concatenations. Each result is a different immutable object.
The older objects become unused after s points to the newest result. The garbage collector may later reclaim them. Garbage collection is the process that finds objects no longer reachable by a program and releases their memory. Creating many temporary strings increases allocation and cleanup work.
The compiler can optimize some concatenations. For example, a fixed expression such as "a" + "b" + "c" can be folded into "abc" before the program runs. That optimization does not generally remove the growing-result problem in a loop whose values are known only while the program runs.
Choosing the Simple Form
Use + or += when the operation is small and easy to read:
public class Main {
public static void main(String[] args) {
String greeting = "Hello, " + "Ada";
String report = "Count: " + 3;
System.out.println(greeting);
System.out.println(report);
}
}For a few values, readability matters more than avoiding a tiny allocation. Replacing every simple concatenation with a more complicated structure can make code harder to understand without producing a meaningful improvement.
The risk appears when a loop repeatedly extends one result:
public class Main {
public static void main(String[] args) {
String result = "";
for (int i = 0; i < 100_000; i++) {
result += i;
}
System.out.println(result.length());
}
}This program may spend substantial time copying increasingly large strings and creating temporary objects. A mutable text-building class, such as StringBuilder, is designed for this pattern because it can grow a buffer and append new characters without creating a new final String on every iteration. Its construction and editing methods are covered in the next chapter.
Practical Rule
Ask how many times the result will grow and how much text it will contain.
- Use
+for a few values or a short expression. - Be cautious with
+=when it appears inside a large loop. - For repeated construction of one result, use a tool designed for mutable text.
- Measure performance when the size or timing actually matters. A small benchmark is more useful than guessing.
Exercise
Why does s += value inside a loop often require more work as the loop continues?
Show answer
String is immutable, so each operation creates a new string and copies the existing characters into it. The amount of copied text grows with each iteration.