Card 08/ 09
All 9 cards
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.
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?
| Loop | Strings created | Characters copied |
|---|---|---|
+= | About a thousand, all but the last discarded | About half a million |
append | One, 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.