Card 06/ 09

ConceptDifficulty: Intermediate1 min

What += Really Does, Once per Pass, Inside a Loop

A method that builds a CSV line out of a thousand values takes a noticeable moment. The same method over ten thousand values takes far more than ten times as long.

java
String row = "";
for (String value : values) {
    row += value + ",";
}

row += value cannot add to row, because nothing can add to a string. What it does instead, on every pass, is build a whole new string containing everything row already held plus the new piece, and then point row at that.

What each pass copies when building a string of n pieces
PassCharacters copiedStrings left for the collector
1The first piece1
2Everything so far, again2
nEverything so far, againn

The work per pass grows with what has already been built, so the total grows with the square of the number of pieces. Ten times the input is a hundred times the copying, which is exactly the shape the timings showed.

A single + between two values is fine and always has been — the cost only appears when the result of one concatenation is the input to the next. That is what a loop does, and it is the one place to reach for a builder instead.