Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Memory allocation of string Builder. What happens in memory? StringBuilder vs String

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();
  1. How much space is reserved for s in the memory ?
  2. I can use it like s[0] = 'a'; so can we call s an array ?
  3. If s is index-based does that mean characters are stored in memory on consecutive locations ?
  4. If answer to 3 is yes. Then what happens if we use 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?
like image 782
Sam Avatar asked May 12 '16 11:05

Sam


1 Answers

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 StringBuilders will be added to the chain when capacity is depleted.

Keeping that in mind, the answers to your specific questions would be:

  1. 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.
  2. Yes, StringBuilder under the hoods uses an array, but each builder in the chain will have its own array.
  3. 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.
  4. 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 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.

like image 162
InBetween Avatar answered Sep 28 '22 18:09

InBetween