Concatenating strings with + inside a loop creates a new String object on every iteration. Since strings are immutable, each + copies the entire accumulated text plus the new piece into a fresh object.
String result = "";
for (int i = 0; i < 1000; i++) {
result = result + i + " ";
}
On the first iteration, Java copies character. On the second, it copies the first chunk plus the new text. By iteration , it is copying thousands of characters just to add a few more. The total work grows with time and creates roughly temporary objects.
With StringBuilder, the internal buffer grows as needed and appends in place:
StringBuilder sb = new StringBuilder();
for (int i = 0; i < 1000; i++) {
sb.append(i).append(" ");
}
String result = sb.toString();
This runs in time and uses space. For any loop that builds a string incrementally, always reach for StringBuilder.