C# StringBuilder CapacityUnderstand how the StringBuilder type manages its capacity as data is added.
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
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
static void Main()
using (var writer = new StreamWriter("data.txt"))
StringBuilder builder = new StringBuilder();
for (int i = 0; i <= 256; i++)
builder.Append("1"); // <-- Add one character
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.
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.CapacityOptimization
© 2007-2020 Sam Allen. Every person is special and unique. Send bug reports to firstname.lastname@example.org.