Why is using + to join strings inside a loop slow in Java?
Each + creates a brand new String and copies all earlier characters, so n appends cost about O(n squared) in total. A StringBuilder keeps one growing buffer and appends in amortised O(1), making the whole loop O(n).
Explain it simply
Imagine writing a long letter, but every time you add one word you must copy the entire letter onto a fresh sheet and throw the old one away. By the 10,000th word you are copying a huge page again and again. StringBuilder is a notebook where you simply keep writing at the end.
Example
// slow: new String every iteration
String s = "";
for (int i = 0; i < 5; i++) {
s += i; // creates a new String each time
}
// fast: one buffer
StringBuilder sb = new StringBuilder();
for (int i = 0; i < 5; i++) {
sb.append(i);
}
System.out.println(sb); // prints: 01234
System.out.println(s); // prints: 01234What to say in the interview
"Strings are immutable, so s += x builds a new String and copies the old content each time. In a loop of n iterations that copying adds up to quadratic time. StringBuilder appends into an internal char buffer that doubles when full, so the total is linear. The compiler does optimise a single expression like a + b + c, but it cannot merge appends across loop iterations."
Common mistakes
- Using StringBuffer by default. It is synchronised and slower, and you rarely need that.
- Optimising one-off concatenation outside loops, where + is perfectly fine.