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 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.