Possibly a duplicate as there are a lot of questions on this topic but I couldn't find what I was looking for.
I know String
is immutable and StringBuilder
is mutable. And I understand the essence of these two terms. I wanted to know what exactly happens in the memory when I create an instance of StringBuilder
. Like:
StringBuilder s = new StringBuilder();
s[0] = 'a';
so can we call s an array ? s.Append("abc");
and there isn't enough consecutive space in memory for "abc"
? Will it take s
to a new memory location just like what happens with string
every time we append something to string
type variable?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:
StringBuilder
and therefore it's underlying array is. You can also specify it with a constructor overload to suit your specific needs.StringBuilder
under the hoods uses an array, but each builder in the chain will have its own array.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 the StringBuilder
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With