3

Why does StringBuilder have a default capacity of 16 characters? Is this some kind of optimization?

StringBuilder builder = new StringBuilder();
Console.WriteLine("builder capacity: '{0}'", builder.Capacity);

output:

builder capacity: '16'
abatishchev
  • 98,240
  • 88
  • 296
  • 433
Darius Kucinskas
  • 10,193
  • 12
  • 57
  • 79
  • See this related question: http://stackoverflow.com/q/246211/25727 – Jan Dec 15 '11 at 14:03
  • 2
    Does it matter? I'm willing to bet someone just chose a reasonable number. – Bernard Dec 15 '11 at 14:03
  • 2
    The main part of my question is WHY? – Darius Kucinskas Dec 15 '11 at 14:05
  • 1
    @DariusKucinskas you mean WHY? – Ray Dec 15 '11 at 14:08
  • 4
    Close as exact duplicate is incorrect in this case. Although I'd be tempted to close as not a real question (although it is, but it doesn't really have a satisfying answer... ;-) – Adam Houldsworth Dec 15 '11 at 14:13
  • 2
    StringBuilder doubles its capacity (http://www.dotnetperls.com/stringbuilder-capacity), when its buffer is not enough to store the modified string. 1st, I think in similar cases every programmer would choose a power of two for the initial size. 2nd, the initial size has to be small enough to handle small strings effectively. 3rd, the average length of an English word (MS is a USA company!) is around 5. In conclusion, the initial length of the internal char array should be a power of 2 close to but larger than 5, that is, 8. Since Unicode char size is 2, the default capacity should be 16 :) – kol Dec 15 '11 at 14:23
  • Because c# copies java ;) – Jean-François Savard Jul 07 '16 at 19:45
  • Thank you @kol, I asked myself the same question this morning. Thanks Darius for asking the question, there is no stupid question. – Andrew Jan 05 '17 at 16:32

1 Answers1

5

Implementation-specific default values are used if no capacity or maximum capacity is specified when an instance of StringBuilder is initialized.

Straight from the MSDN docs.

They can't really optimise anything as it depends entirely on usage, hence they let you specify a capacity in the constructor, so you can optimise it yourself. They put something in if you don't specify anything purely on the fairly-safe guess that you want some capacity even if you don't specify any.

The same goes for lists. They don't know how many items you want or how many items on average a list contains in your app. They expose capacity so you can force the list size to something that would prevent it from having to grow too often. The StringBuilder is no different in this case.

Adam Houldsworth
  • 63,413
  • 11
  • 150
  • 187