How the StringBuilder class is implemented? Does it internally create new string objects each time we append?

Viewed 15491

How the StringBuilder class is implemented? Does it internally create new string objects each time we append?

6 Answers

The accepted answer misses the mark by a mile. The significant change to StringBuilder in 4.0 is not the change from an unsafe string to char[] - it's the fact that StringBuilder is now actually a linked-list of StringBuilder instances.


The reason for this change should be obvious: now there is never a need to reallocate the buffer (an expensive operation, since, along with allocating more memory, you also have to copy all the contents from the old buffer to the new one).

This means calling ToString() is now slightly slower, since the final string needs to be computed, but doing a large number of Append() operations is now significantly faster. This fits in with the typical use-case for StringBuilder: a lot of calls to Append(), followed by a single call to ToString().


You can find benchmarks here. The conclusion? The new linked-list StringBuilder uses marginally more memory, but is significantly faster for the typical use-case.

Related