Card 08/ 09

ExerciseDifficulty: Intermediate1 min

How Many Objects Does This Loop Create

Two loops that produce the same final text. Before opening the reveal, write down roughly how many String objects each one leaves behind for the garbage collector.

java
String a = "";
for (int i = 0; i < 1000; i++) {
    a += "x";
}

StringBuilder b = new StringBuilder();
for (int i = 0; i < 1000; i++) {
    b.append("x");
}
String result = b.toString();
How many strings does each loop leave behind, and what does that cost?
Objects created and characters copied by each loop
LoopStrings createdCharacters copied
+=About a thousand, all but the last discardedAbout half a million
appendOne, at the end, from toString()About a thousand, plus a few array copies as it grows

The character count is the number that matters. Each pass of the first loop copies everything built so far, so the totals are 1 + 2 + 3 and so on up to a thousand — which comes to around five hundred thousand.

The builder keeps one array and writes into the end of it, so the only copying is when the array is too small and has to be replaced, which happens a handful of times rather than a thousand.