Card 08/ 09

ExerciseDifficulty: Intermediate1 min

Practice: Counting the Strings a Loop Creates

The same thousand-character result from += and from append, and very different work.

Each += on a string creates a new string and copies everything so far; a StringBuilder writes into one array. Using that, write down roughly how many String objects each of the two loops below leaves behind, and how many characters each copies, before opening the answer.

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.