Memory allocation of string Builder. What happens in memory? StringBuilder vs String
A StringBuilder
is in reality, under the hoods, a chain of StringBuilders
(think of them as chained blocks of memory). The user is apparently interacting with one single StringBuilder
but that is far from true.
Each StringBuilder
uses an underlying char
array and new StringBuilder
s will be added to the chain when capacity is depleted.
Keeping that in mind, the answers to your specific questions would be:
- Check out the implementation to see what the default capacity of a
StringBuilder
and therefore it's underlying array is. You can also specify it with a constructor overload to suit your specific needs. - Yes,
StringBuilder
under the hoods uses an array, but each builder in the chain will have its own array. - Yes and no. Memory for the array of each internal builder in the chain is allocated consecutively, but the different memory blocks need not be and most likely will not be allocated consecutively.
- When there isn't enough space a new
StringBuilder
is added to the chain and its corresponding array is allocated wherever the runtime sees fit; typically the new builder will at least double the total capacity of theStringBuilder
and the new array will most likely not be allocated consecutively to the previous one.
Obviously this system allows dynamic resizing while avoiding the costs associated with resizing arrays and copying data back and forth.