StringBuilder
Why a builder
A string is immutable, so text += part in a loop
allocates a new string on every pass and copies the text built so far. For
three parts that is nothing; for a report of a thousand lines it is a
quadratic amount of copying.
StringBuilder is a mutable buffer: it holds an
array of characters, appends into it, and turns into a string once at the
end. It is in System.Text, which is not one of the
implicit namespaces, so a file with a builder starts with
using System.Text;.
Append, Insert and the capacity
using System.Text;
var builder = new StringBuilder();
Console.WriteLine($"capacity: {builder.Capacity}");
builder.Append("order");
builder.Append(' ').Append(42);
builder.AppendLine(" items");
builder.Insert(0, "> ");
Console.WriteLine(builder.ToString().TrimEnd());
Console.WriteLine($"length: {builder.Length} capacity: {builder.Capacity}");
builder.Clear();
Console.WriteLine($"after clear: {builder.Length}");
dotnet run
capacity: 16
> order 42 items
length: 17 capacity: 18
after clear: 0
Four numbers are worth reading. The new builder starts with a capacity of
16 characters and a length of 0. Append takes any
object, because every type has ToString: the
42 needed no conversion.
AppendLine adds Environment.NewLine,
which is why the last character was a line break and
TrimEnd removed it for the print.
Insert(0, ...) put a prefix in front of everything
that was already there.
The capacity grew from 16 to 18 to hold the 17 characters, and
Clear set the length to 0 without giving the buffer
back. The growth is why a program that knows the size should say so:
new StringBuilder(capacity: 4096) allocates once and
saves the copying.
A builder, a join or a plus
Three pieces of code build the same kind of text, and each has a case where it is the right one:
using System.Text;
var parts = new List<string>();
for (int i = 1; i <= 4; i++)
{
parts.Add($"item{i}");
}
string joined = string.Join(", ", parts);
Console.WriteLine(joined);
string text = "";
for (int i = 0; i < 3; i++)
{
text += i;
}
Console.WriteLine(text);
var report = new StringBuilder();
foreach (var part in parts)
{
report.Append(part).Append(';');
}
Console.WriteLine(report.ToString());
dotnet run
item1, item2, item3, item4
012
item1;item2;item3;item4;
- string.Join is the shortest way when the pieces are already in a collection and only a separator is missing.
- A + chain is right for a fixed number of parts, as in a message built from three values; the compiler turns it into one concatenation call.
- A builder is right for a loop whose count is not known and where each pass adds a piece, such as a report written line by line.
The part on performance measures all three on the same job.
Exercises
- Append the numbers 1 to 100 to an empty builder without a separator and print the length. Then append them with a comma and compare.
- Create a builder with a capacity of 1000 and print its capacity after ten appends. Why does it not change?
- Replace the loop of the second program with string.Concat and compare the source.
- Call ToString() on a builder, append once more, and print the first string again. Does it change?
Questions
A new set of questions in a new order every time. Choose one answer for each, then check.
-
Why is a StringBuilder faster than adding to a string in a loop?
Answer
It appends into one mutable buffer instead of copying a new string each time
A string is immutable, so each += copies the whole text; a builder grows one buffer and produces the string once.
-
Which namespace holds StringBuilder?
Answer
System.Text
StringBuilder is in System.Text, which is not implicit, so the file needs a using for it.
-
What does this program print?
using System.Text; var builder = new StringBuilder("ab"); builder.Append("cd"); Console.WriteLine(builder.Length);Answer
4
The builder starts with two characters and two more are appended, so the length is 4.
-
What does this program print?
using System.Text; var builder = new StringBuilder("abc"); builder.Insert(0, "> "); Console.WriteLine(builder.ToString().ToUpper());Answer
> ABC
Insert puts the prefix in front, and ToUpper uppercases the whole text including the prefix symbols.
-
What does Clear do to a StringBuilder?
Answer
It sets the length to 0 and keeps the buffer
Clear empties the text but the buffer stays for reuse, so the capacity usually does not change.
-
What does this program print?
using System.Text; var builder = new StringBuilder(); Console.WriteLine(builder.Length); Console.WriteLine(builder.Capacity);Answer
0 / 16
A new builder of this runtime has an empty text and a buffer of 16 characters, which is what it printed here.
-
Which is the shortest way to join a list with a separator?
Answer
string.Join
string.Join takes the separator and the collection and does the loop itself, which is both shorter and allocation-aware.
-
What does this program print?
using System.Text; var builder = new StringBuilder("a"); builder.Append('b').Append(1); Console.WriteLine(builder.ToString());Answer
ab1
Append returns the same builder, so the calls chain, and an int is appended as its text.
-
What happens to a string taken from a builder before another Append?
Answer
It keeps its characters, because ToString returned a separate immutable string
ToString copies the buffer into a new immutable string, so later appends cannot change the string already taken.
-
When is a plus chain the right tool?
Answer
For a fixed small number of parts, such as a message from three values
A few parts are one concatenation call and read better as +; the loop with an unknown count is where a builder earns its place.
The code on this page was built with the .NET SDK 10.0.303 and run on Alpine Linux 3.24.3 (x86_64) in a Docker container.
Article author: Arthur Isaev