Home

Search

C# StringBuilder CapacityUnderstand how the StringBuilder type manages its capacity as data is added.
dot net perls

StringBuilder capacity. StringBuilder in .NET allocates its capacity. When it runs out of space to Append characters, it reallocates and copies the data, leading to slowdowns. It uses a clever algorithm for this.

StringBuilder

Example. The graph shows that StringBuilder doubles its capacity. It reallocates its buffers so it can store twice as many characters each time. The algorithm resizes the buffer when you add the 17th character and the 33rd character.

StringBuilder Append

Program This is a simple console program in C# that loops through 257 integers, 0 to 256 inclusive.

And It writes the Capacity and Length of the StringBuilder, and then appends one character.

Note The output shows in the first column the Capacity. And in the second column, we see the buffer Length.

Tip To append a single character, it is more efficient to use a char instead of a single-character string.

StringBuilder Data Types

C# program that tests StringBuilder capacity
using System.IO; using System.Text; class Program { static void Main() { using (var writer = new StreamWriter("data.txt")) { StringBuilder builder = new StringBuilder(); for (int i = 0; i <= 256; i++) { writer.Write(builder.Capacity); writer.Write(","); writer.Write(builder.Length); writer.WriteLine(); builder.Append("1"); // <-- Add one character } } } }
16, 0 16, 1 16, 2 16, 3 16, 4 16, 5 16, 6 16, 7 16, 8 16, 9 16,10 16,11 16,12 16,13 16,14 16,15 16,16 32,17 32,18 32,19 32,20 32,21 32,22 32,23 32,24 32,25 32,26 32,27 32,28 32,29 32,30 32,31 32,32 64,33

Notes, IL. As a busy .NET developer, you would want to open the StringBuilder Append method in the IL Disassembler. Then you could examine the internal instructions the class uses to manage its buffer.

Summary. We saw a visualization and demonstration of how StringBuilder doubles its buffer size. In many programs, the StringBuilder will reallocate itself several times at the smallest sizes, and then fewer times as it grows larger.

Capacity

Home
© 2007-2021 sam allen. send bug reports to info@dotnetperls.com.