Question

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'
Was it helpful?

Solution

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.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top