Scrivio Interview library
CodingFoundations6 min read · updated 12 November 2026

Rewrite this for performance and explain the cost of the original:

Java
String csv = "";
for (String item : items) {
csv += item + ",";
}

Each csv += item + "," creates a brand-new String and copies every character built so far, so the loop does work proportional to the square of the final length. The fix is to build the text once: String.join(",", items) or items.stream().collect(Collectors.joining(",")) for the simple case, or a single StringBuilder created before the loop, pre-sized when we can estimate the length. invokedynamic concatenation makes each single expression efficient but cannot remove the copy of the growing string on every iteration.

Why this question is asked

String concatenation in a loop is one of the most common performance bugs in Java code, and it hides well: with ten items it is instant, with a hundred thousand it can take seconds and allocate gigabytes. Interviewers use it to check that we understand immutability in practice and can count the work a loop really does. In this answer, we will measure what the original loop costs, rewrite it three ways, see why pre-sizing a builder helps, and explain why the modern compiler optimisation for + does not save this loop. We will also notice a small bug in the original.

1A Quick Recap: Why += Copies

A String is immutable, so csv += x cannot add to the existing string. It creates a new String big enough for both parts, copies the old characters into it, copies the new ones after them, and points csv at the result. The old String becomes garbage.

Inside one iteration that is fine. The problem is that the old part grows every time round the loop, and every iteration copies all of it again.

2Counting the Cost of the Original Loop

Suppose items has 10,000 entries of 10 characters each. Each iteration adds 11 characters (the item and a comma). On iteration i, the new string has about 11 x i characters, and all of them are copied.

Java
String csv = "";
for (String item : items) { // 10,000 items of 10 chars
csv += item + ","; // iteration i copies about 11 * i chars
}
// final length: 110,000 chars
// chars copied: 11 * (1 + 2 + ... + 10,000) = about 550,000,000
// garbage created: 10,000 intermediate Strings, about 550 MB of Latin-1 bytes in total
Work done by the loop as items grow
Items (10 chars each)Final lengthChars copied by +=Chars copied by a builder
1001,100about 55,000about 1,100
10,000110,000about 550 millionabout 110,000 plus growth
100,0001.1 millionabout 55 billionabout 1.1 million plus growth
The += column grows with the square of the input; the builder column grows linearly.

So to produce 110,000 characters, the loop copies about 550 million, five thousand times more work than needed, and creates hundreds of megabytes of short-lived garbage. Doubling the number of items roughly quadruples the time. That is what O(n squared) in the total length means in practice. Notice also that the result ends with a trailing comma, which is almost never what we want for CSV.

3Rewrite 1: String.join or Collectors.joining

For the common case of joining strings with a separator, the JDK already has the answer, and it also fixes the trailing comma, because a separator goes only between elements.

Java
List<String> items = List.of("a", "b", "c");
String csv1 = String.join(",", items); // a,b,c
String csv2 = items.stream().collect(Collectors.joining(",")); // a,b,c
String csv3 = items.stream().map(String::toUpperCase)
.collect(Collectors.joining(",", "[", "]")); // [A,B,C]

String.join and Collectors.joining use a StringJoiner internally, which adds each piece once. Collectors.joining is handy when we transform elements on the way, and its three-argument form adds a prefix and suffix.

4Rewrite 2: One StringBuilder, Pre-Sized

When each element needs more work than a separator, we use a single StringBuilder created before the loop. append adds to its internal array in place, so each character is copied into the builder once.

Java
StringBuilder sb = new StringBuilder(items.size() * 11); // estimate: 10 chars + comma per item
for (String item : items) {
if (sb.length() > 0) sb.append(','); // separator only between items
sb.append(item);
}
String csv = sb.toString(); // a,b,c for the small list

The builder's array still has to grow when it fills: its default capacity is 16 characters, and each time it runs out it allocates an array about twice as large and copies the contents. Growth by doubling keeps the total copying linear, but for large output it still means several big allocations. Passing an estimated capacity to the constructor, here items.size() * 11, avoids most of them. A rough estimate is enough; if it is too small the builder grows as usual.

5Why invokedynamic Does Not Save the Loop

Since JDK 9, javac compiles a concatenation expression into an invokedynamic call handled by StringConcatFactory. The JDK computes the exact size of the result for that one expression and copies each part once. So csv += item + "," is compiled as one concatenation of three parts, csv, item and ",", which is better than the JDK 8 code that created a temporary StringBuilder for each iteration.

But notice what the three parts are. The first part is csv, the whole string built so far. The optimisation makes one iteration as cheap as possible, yet that iteration still has to copy all of csv into a new String, because the result is a new immutable object. The compiler optimises each expression in isolation and cannot turn a loop of new Strings into one growing buffer. That is a change only we can make, by keeping the mutable builder outside the loop.

6Follow-up questions

Does the JIT ever optimise this loop away?

No. The JIT can remove some allocations in straight-line code, but here each iteration's result is needed by the next one, and its size keeps growing, so the copying remains. Measurements with JMH show the quadratic behaviour clearly once the list has a few thousand items.

Is String.join slower than a hand-written StringBuilder?

Not in any way that matters. It uses StringJoiner, which collects the pieces and builds the result with one allocation of the exact size in recent JDKs. Its main advantage is clarity: there is no separator logic to get wrong.

What if the CSV values can contain commas or quotes?

Then joining is not enough, because a value like Smith, John breaks the columns. Real CSV needs quoting and escaping, so for anything beyond simple identifiers we use a CSV library or at least a helper that quotes values containing commas, quotes or newlines.

7Conclusion

In this answer, we saw that += on a String in a loop creates a new String and copies everything built so far on every iteration, so 10,000 items of 10 characters cost about 550 million character copies for a 110,000-character result. We rewrote it with String.join or Collectors.joining, which also removes the trailing comma, and with one pre-sized StringBuilder outside the loop. invokedynamic concatenation makes each expression efficient, but it cannot avoid copying the growing string on each iteration, because only a builder kept outside the loop can do that.

What to say in the interviewAbout 90 seconds aloud

Open with

The original loop is quadratic. Strings are immutable, so each plus-equals creates a new String and copies everything built so far, then adds the item and the comma.

Then, if they want more

On iteration i it copies about i items' worth of text, so for 10,000 items of 10 characters it copies roughly 550 million characters and creates ten thousand throwaway strings, just to produce 110,000 characters. Double the input and it takes four times as long. It also leaves a trailing comma.

My rewrite for this exact case is String.join with a comma over the list, or Collectors.joining if I am transforming the items in a stream. Both add a separator only between elements and copy each piece once.

If each item needs more logic, I use one StringBuilder created before the loop, sized roughly to the expected length, say the number of items times eleven, so it does not have to keep doubling and copying its array, and I append the separator only when the builder is not empty.

Someone might say the compiler optimises plus since Java 9 with invokedynamic. It does, but per expression: it makes a single concatenation compute its exact size, and here one of the parts is the whole accumulated string, so every iteration still copies all of it. Only moving to a builder outside the loop fixes that.

About this answer

Last updated
12 November 2026
Versions it names
Java 8, Java 9
Checked
Its structure and format are checked automatically. Use it as a carefully prepared study note: where a detail matters, confirm it against the documentation below. What the checks cover
Where the question comes from
Written by Scrivio for practice. It is not taken from an interview.
Report an issue with this answer

Copy the line below and send it to the author with what you found. It carries the address of this page.

Issue with "Rewrite this for performance and explain the cost of the original:": https://scrivio-interview-library.netlify.app/java/strings/5f04b34815/