Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does StringBuilder have a default capacity of 16 characters?

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'
like image 693
Darius Kucinskas Avatar asked Jan 25 '26 07:01

Darius Kucinskas


1 Answers

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.

like image 106
Adam Houldsworth Avatar answered Jan 27 '26 21:01

Adam Houldsworth



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!