Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How does StringBuilder's capacity change?

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).

like image 767
Vlad Vivdovitch Avatar asked Sep 25 '11 18:09

Vlad Vivdovitch


People also ask

What is the capacity of a StringBuilder object?

The default capacity of StringBuilder class is 16 bytes. Syntax: int capacity(): This method returns the capacity of the StringBuilder object. The default capacity of the StringBuilder is 16 bytes.

What is the maximum size of StringBuilder in Java?

Here because of parameter as int the maximum capacity that a StringBuilder Class can is reach will be 2147483647 .

What is capacity in StringBuilder C#?

The default capacity of a StringBuilder object is 16 characters, and its default maximum capacity is Int32.

How do you measure the length of a StringBuilder?

The length() method of StringBuilder class returns the number of character the StringBuilder object contains. The length of the sequence of characters currently represented by this StringBuilder object is returned by this method.


2 Answers

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.

like image 120
Hans Passant Avatar answered Sep 28 '22 05:09

Hans Passant


The C# standard will not specify the behavior of a BCL library class as it has nothing to do with the language specification.

As far as I know the actual behavior is not defined in any specification and is implementation specific.

AFAIK, The MS implementation will double the capacity once the current capacity has been reached.

See this and this previous SO questions.


Update:

This has been changed in .NET 4.0. as described by Hans in his answer. Now ropes are used, adding additional 8000 characters at a time.

MSDN, however is very careful to point out that the actual behavior is implementation specific:

The StringBuilder dynamically allocates more space when required and increases Capacity accordingly. For performance reasons, a StringBuilder might allocate more memory than needed. The amount of memory allocated is implementation-specific.

like image 22
Oded Avatar answered Sep 28 '22 06:09

Oded