When I have an empty StringBuilder
with a capacity of 5 and I write "hello, world!" to it, does the C# standard specify the new capacity of the StringBuilder
? I have a vague memory that it's twice the new string's length (to avoid changing the capacity with every new appended string).
Depends what version of .NET you're talking about. Prior to .NET 4, StringBuilder used the standard .NET strategy, doubling the capacity of the internal buffer every time it needs to be enlarged.
StringBuilder was completely rewritten for .NET 4, now using ropes. Extending the allocation is now done by adding another piece of rope of up to 8000 chars. Not quite as efficient as the earlier strategy but avoids trouble with big buffers clogging up the Large Object Heap. Source code is available from the Reference Source if you want to take a closer look.