Sub topic 2
The Cost of Concatenating in a Loop
This chapter assumes you know basic Java syntax (variables, loops, methods) and that String objects are immutable, as covered in the previous chapter. You should also be able to compile and run a single-file program with a recent JDK. Here you will see why s += x inside a loop is slow, how to measure that cost, and where concatenation is still the right choice.
The Pattern in Question
This code looks harmless:
String s = "";
for (int i = 0; i < 5; i++) {
s += i;
}
System.out.println(s); // 01234The += operator does not change s. It cannot, because a String never changes after it is created. Instead, s += i means s = s + i. Java builds a new String that holds the old characters followed by the new ones, then makes the variable s point at it. The old String becomes garbage.
For five iterations this is irrelevant. The trouble starts when the loop is long, because each iteration copies everything accumulated so far.
What Happens in Each Iteration
Suppose the loop appends one character per iteration. On iteration k, the existing string holds k - 1 characters. Producing the new string means:
- Allocating a new internal array large enough for
kcharacters. - Copying the
k - 1existing characters into it. - Writing the one new character.
- Updating the reference
sto point at the new object.
Add up the copying over n iterations: 0 + 1 + 2 + ... + (n - 1), which is n(n - 1) / 2 characters copied. That grows with the square of n, so the work is O(n²). Doubling the number of iterations roughly quadruples the copying.
| Iterations (n) | Characters copied (about n²/2) |
|---|---|
| 1,000 | 500,000 |
| 10,000 | 50,000,000 |
| 100,000 | 5,000,000,000 |
Memory allocation grows the same way. Each iteration allocates an array that is slightly bigger than the last one, so the garbage collector has a steady supply of short-lived large objects to clean up. A loop that builds a 100,000-character string allocates on the order of 5 GB in total, even though the final result is only 100 KB.
Measuring It
Rather than trust the arithmetic, run it. This program times both approaches for increasing sizes. StringBuilder is introduced properly in the next chapter. Here it only serves as a baseline.
public class ConcatCost {
static String withConcat(int n) {
String s = "";
for (int i = 0; i < n; i++) {
s += 'x';
}
return s;
}
static String withBuilder(int n) {
StringBuilder sb = new StringBuilder();
for (int i = 0; i < n; i++) {
sb.append('x');
}
return sb.toString();
}
static long timeMillis(java.util.function.IntFunction<String> task, int n) {
long start = System.nanoTime();
String result = task.apply(n);
long elapsed = System.nanoTime() - start;
if (result.length() != n) {
throw new IllegalStateException("unexpected length");
}
return elapsed / 1_000_000;
}
public static void main(String[] args) {
// Warm-up so the JIT compiler has seen both methods.
timeMillis(ConcatCost::withConcat, 5_000);
timeMillis(ConcatCost::withBuilder, 5_000);
int[] sizes = {10_000, 20_000, 40_000, 80_000, 160_000};
System.out.printf("%8s %10s %10s%n", "n", "concat ms", "builder ms");
for (int n : sizes) {
long concat = timeMillis(ConcatCost::withConcat, n);
long builder = timeMillis(ConcatCost::withBuilder, n);
System.out.printf("%8d %10d %10d%n", n, concat, builder);
}
}
}Save it as ConcatCost.java and run it with java ConcatCost.java. The exact numbers depend on your hardware and JDK, so treat any specific figure as illustrative. The shape of the results is what matters. The concatenation column should grow by roughly four times each time n doubles, while the builder column stays near zero and grows roughly in step with n.
What the Compiler Does, and Does Not, Fix
A common belief is that "the compiler turns + into StringBuilder, so it is fine." That is half true, and the half that is false is the part that matters in loops.
- Java 8 and earlier:
javacrewrote each concatenation expression intonew StringBuilder().append(a).append(b).toString(). Inside a loop, that happened once per iteration, so every iteration still created a fresh builder, copied the whole accumulated string into it, and produced another newString. - Java 9 and later:
javacemits aninvokedynamiccall toStringConcatFactory. The runtime chooses a strategy, usually one that computes the exact result size and fills a single array. This makes a single expression such asa + b + c + dcheaper than before.
Neither approach spans loop iterations. The compiler sees one concatenation expression and optimizes it, but it does not know that the result feeds back into the same variable on the next pass. Each iteration is still one full copy.
You can see this yourself by compiling a class and running javap -c ConcatCost. Look inside withConcat: the concatenation instruction sits inside the loop body, and a new string is produced on every pass.
The JIT compiler can sometimes remove temporary objects through escape analysis. It cannot turn an accumulating loop into a linear one. Do not rely on it for this.
Where Concatenation Is Fine
The problem is the accumulator: a variable that grows across iterations and is copied each time. Plain concatenation remains the clearest choice in these cases.
A single expression, even a long one.
String label = firstName + " " + lastName + " (" + age + ")";This is one concatenation. The compiler handles it efficiently, and it is far more readable than a chain of append calls.
A short string built per iteration, not accumulated.
for (String name : names) {
System.out.println("Hello, " + name + "!");
}Each iteration creates a small independent string whose size does not depend on the iteration count. The total cost is linear.
Compile-time constants. Concatenating constants costs nothing at run time, because the compiler folds them into one literal:
static final String PREFIX = "app" + "." + "config"; // becomes "app.config"A small, bounded number of iterations. If a loop runs at most a handful of times, such as building a string from three command-line arguments, the quadratic term never gets large enough to matter. Clarity wins.
Semantics You Should Know
Because += on a String is shorthand for a concatenation, the usual rules of the + operator apply, and some of them surprise people inside loops.
Evaluation is left to right, and types matter
If either operand of + is a String, the other is converted to text. If neither is, + does arithmetic. Compare:
public class PlusRules {
public static void main(String[] args) {
String a = "";
a += 'a' + 1; // 'a' + 1 is int arithmetic: 98
System.out.println(a); // 98
String b = "";
b += 'a';
b += 1;
System.out.println(b); // a1
String c = 1 + 2 + "x" + 1 + 2;
System.out.println(c); // 3x12
String d = null;
d += "!";
System.out.println(d); // null!
}
}In the first case, the right-hand side of += is evaluated first, and 'a' + 1 is an int. In the third case, 1 + 2 is evaluated before it meets the string, so it becomes 3. In the last case, a null reference converts to the text "null" rather than throwing an exception.
Each `+=` is a separate copy
Two concatenations in one statement are cheaper than two statements:
s += a + b; // one concatenation of s with (a + b), copies s once
s += a; s += b; // two concatenations, copies s twiceIn the first line, a + b is evaluated on its own first. If both are strings, that is a small concatenation. Then s is copied once. In the second form, s is copied twice. Inside a loop, grouping the pieces can cut the cost, but it does not change the quadratic shape.
A Realistic Example
Here is a method that formats a list of values as a comma-separated line, written the naive way:
import java.util.List;
public class CsvLine {
static String toCsv(List<Integer> values) {
String line = "";
for (int i = 0; i < values.size(); i++) {
if (i > 0) {
line += ",";
}
line += values.get(i);
}
return line;
}
public static void main(String[] args) {
System.out.println(toCsv(List.of(3, 1, 4, 1, 5))); // 3,1,4,1,5
}
}It produces the right output. It also performs two full copies of line per iteration, so it is a poor choice for a list of 50,000 values. Note that if the list is huge this is not only slow but also churns through memory.
The standard library already has a better tool for this exact job. Joining a collection of values with a delimiter is what String.join and Collectors.joining are for:
import java.util.List;
import java.util.stream.Collectors;
public class CsvJoin {
public static void main(String[] args) {
List<Integer> values = List.of(3, 1, 4, 1, 5);
String line = values.stream()
.map(String::valueOf)
.collect(Collectors.joining(","));
System.out.println(line); // 3,1,4,1,5
}
}String.join(",", strings) does the same for an Iterable<? extends CharSequence> or varargs of CharSequence. Use it when the input is already strings. Use Collectors.joining when you need to map or filter first. Both build their result in one pass. The next chapter shows the more general tool, StringBuilder, for cases where joining does not fit, for example when the formatting differs from one iteration to the next.
Symptoms and Diagnosis
If you suspect concatenation in a loop in existing code, look for these signs:
- A method that takes seconds on large input but is instant on small input, with time growing faster than the input size.
- A profiler or GC log showing a high allocation rate of
byte[]orchar[]arrays, with many large short-lived arrays. - A
Stringvariable declared outside a loop and modified with+=ors = s + ...inside it. - Loops that run once per line of a file, once per row of a query result, or once per element of a user-supplied collection. These are the places where
nis not bounded by you.
Many static analysis tools and IDE inspections flag String concatenation in a loop. Treat such a warning as a prompt to check how large n can get, not as an automatic defect.
Summary of the Cost Model
Stringis immutable, so every concatenation produces a new object and copies the existing characters.- Accumulating in a loop copies a growing prefix each time, giving O(n²) total work and O(n²) total allocation.
- The compiler optimizes a single concatenation expression, but it does not turn a loop into a linear build.
- Single expressions, small bounded loops and compile-time constants are fine as they are.
- For delimiter-separated output, prefer
String.joinorCollectors.joining. For everything else that accumulates, use aStringBuilder, the subject of the next chapter.
Exercise
A loop runs 40,000 iterations and appends one character to a String with s += c each time. Roughly how many characters are copied in total, and what happens to that number if the loop is changed to run 80,000 iterations?
Show answer
About n²/2 characters are copied: 40,000² / 2 = 800,000,000. At 80,000 iterations the figure is 80,000² / 2 = 3,200,000,000, which is four times as many. Doubling the input quadruples the copying because the cost is O(n²).
Exercise
What does this code print, and why? String s = ""; s += 'a' + 'b'; s += "c"; System.out.println(s);
Show answer
It prints 195c. The expression 'a' + 'b' is evaluated first, and since both operands are char values and neither is a String, it is integer addition: 97 + 98 = 195. That number is then appended to the empty string as "195", and "c" is appended after it.
Exercise
Which of these is a problem in a loop, and which is fine? (1) String row = id + "," + name + "," + score; executed once per input line. (2) report += row + "\n"; executed once per input line, where report is declared before the loop.
Show answer
(1) is fine. It builds one small independent string per iteration, and the cost does not depend on how many lines were already processed. (2) is the problem. report is an accumulator that is copied in full on every iteration, so the total work grows with the square of the number of lines.