Reputation: 10661
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'
Upvotes: 3
Views: 2696
Reputation: 64467
Implementation-specific default values are used if no capacity or maximum capacity is specified when an instance of StringBuilder is initialized.
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.
Upvotes: 5