String concatenation
A string is immutable: a + b allocates a new string and copies both parts into it. Once is nothing; in a loop over a thousand parts it copies the whole text a thousand times, and the total is quadratic in the length. The lesson measures the three ways a program builds a string.
A chain of +
The loop appends two thousand short strings to one variable. Every iteration allocates the concatenation of everything so far and the next part, and the previous result becomes garbage:
var parts = Enumerable.Range(0, 2000).Select(i => i.ToString()).ToArray();
var text = "";
for (var i = 0; i < parts.Length; i++)
{
text += parts[i];
}
Console.WriteLine($"length {text.Length}");
dotnet run
length 6890
The result is 6 890 characters and the loop copied 1+2+3+...+6890 characters in total, about 23 million. The compiler turns a + b + c written in one expression into a single call to string.Concat, which is fine; the problem is the variable that is reassigned in a loop.
StringBuilder
StringBuilder keeps a mutable buffer and grows it when it fills. Append writes into the buffer and ToString copies the result once:
using System.Text;
var parts = Enumerable.Range(0, 2000).Select(i => i.ToString()).ToArray();
var builder = new StringBuilder();
for (var i = 0; i < parts.Length; i++)
{
builder.Append(parts[i]);
}
var text = builder.ToString();
Console.WriteLine($"length {text.Length} capacity {builder.Capacity}");
dotnet run
length 6890 capacity 8192
The buffer doubled from sixteen until it held the text, and the final capacity is 8 192. A program that knows the approximate length passes it to the constructor, new StringBuilder(7000), and avoids the last few copies. The single ToString is the one allocation that remains.
string.Join
When the parts already exist as a collection, string.Join is the shortest and the fastest: it counts the lengths, allocates the result once and fills it:
var parts = Enumerable.Range(0, 2000).Select(i => i.ToString()).ToArray();
var text = string.Join("", parts);
Console.WriteLine($"length {text.Length}");
dotnet run
length 6890
A separator is the first argument, and an empty string joins without one. The method is the right choice for a report line or a CSV row, where the parts are already a list; a loop that computes each part uses a StringBuilder instead.
The measured numbers
The three ways were measured in one program, five runs each, after a single warm-up on the first loop. The listing is the measured program:
using System.Diagnostics;
using System.Text;
const int Count = 2000;
var parts = Enumerable.Range(0, Count).Select(i => i.ToString()).ToArray();
var plusRuns = new List<double>();
var builderRuns = new List<double>();
var joinRuns = new List<double>();
for (var run = 0; run < 5; run++)
{
var watch = Stopwatch.StartNew();
var text = "";
for (var i = 0; i < Count; i++)
{
text += parts[i];
}
watch.Stop();
plusRuns.Add(watch.Elapsed.TotalMilliseconds);
watch = Stopwatch.StartNew();
var builder = new StringBuilder();
for (var i = 0; i < Count; i++)
{
builder.Append(parts[i]);
}
text = builder.ToString();
watch.Stop();
builderRuns.Add(watch.Elapsed.TotalMilliseconds);
watch = Stopwatch.StartNew();
text = string.Join("", parts);
watch.Stop();
joinRuns.Add(watch.Elapsed.TotalMilliseconds);
Console.WriteLine($"run {run + 1} plus {plusRuns[^1]:F2} builder {builderRuns[^1]:F2} join {joinRuns[^1]:F2} {text.Length}");
}
var before = GC.GetAllocatedBytesForCurrentThread();
var check = "";
for (var i = 0; i < Count; i++)
{
check += parts[i];
}
var plusBytes = GC.GetAllocatedBytesForCurrentThread() - before;
before = GC.GetAllocatedBytesForCurrentThread();
var buffer = new StringBuilder();
for (var i = 0; i < Count; i++)
{
buffer.Append(parts[i]);
}
var built = buffer.ToString();
var builderBytes = GC.GetAllocatedBytesForCurrentThread() - before;
Console.WriteLine($"plus min {plusRuns.Min():F2} median {plusRuns.Order().ElementAt(2):F2}");
Console.WriteLine($"builder min {builderRuns.Min():F2} median {builderRuns.Order().ElementAt(2):F2}");
Console.WriteLine($"join min {joinRuns.Min():F2} median {joinRuns.Order().ElementAt(2):F2}");
Console.WriteLine($"plus bytes {plusBytes}");
Console.WriteLine($"builder bytes {builderBytes}");
Console.WriteLine($"same {check == built}");
dotnet run
run 1 plus 6.10 builder 0.38 join 0.13 6890
run 2 plus 3.82 builder 0.04 join 0.04 6890
run 3 plus 3.40 builder 0.07 join 0.03 6890
run 4 plus 4.71 builder 0.04 join 0.03 6890
run 5 plus 5.10 builder 0.07 join 0.10 6890
plus min 3.40 median 4.71
builder min 0.04 median 0.07
join min 0.03 median 0.04
plus bytes 12630056
builder bytes 30912
same True
| Way | Min ms | Median ms | Bytes allocated |
|---|---|---|---|
| + in a loop | 3.40 | 4.71 | 12 630 056 |
| StringBuilder | 0.04 | 0.07 | 30 912 |
| string.Join | 0.03 | 0.04 | one result |
The plus chain allocated 12.6 MB for a 6.9 KB string, the builder 30 912 bytes, which is its buffer plus the result, and Join allocates the result and nothing else. The time gap is more than sixty times on this run, and it grows with the length of the text: the allocation and the copying are the cause, not the method call.
Exercises
- Give the StringBuilder a capacity of 7 000 and print the capacity at the end.
- Replace the loop with string.Concat(parts) and measure it.
- Join the same parts with a comma and compare the length.
- Run the plus loop with five thousand parts and compare the allocation with the two-thousand one.
Questions
A new set of questions in a new order every time. Choose one answer for each, then check.
-
Why is a chain of + in a loop slow?
Answer
Every iteration copies the whole text built so far
The measured 12.6 MB for a 6.9 KB result is that copying.
-
What does StringBuilder do differently?
Answer
It appends into a mutable buffer and copies once at ToString
The buffer grows as needed, and the result is one allocation.
-
What does this program print?
var s = "a"; s += "b"; Console.WriteLine(s);Answer
ab
The assignment stores the new string in the variable.
-
How many bytes did the plus loop allocate for 2000 parts?
Answer
12 630 056
The measured line on the page is plus bytes 12630056.
-
What does string.Join do?
Answer
Joins the parts with a separator, allocating the result once
It is the shortest way when the parts are already a collection.
-
What does this program print?
Console.WriteLine(string.Join("-", new[] { "a", "b" }));Answer
a-b
The separator is inserted between the two parts.
-
What capacity should a StringBuilder be created with?
Answer
An estimate of the final length
A good estimate avoids the growth copies; the exact length is not required.
-
What does this program print?
using System.Text; Console.WriteLine(new StringBuilder().Append("a").Append(1).Length);Answer
2
The builder holds the character a and the character 1.
-
Is a string mutable?
Answer
No, every change creates a new string
Immutability is what makes the plus chain copy each time.
-
What does this program print?
Console.WriteLine(2000.ToString().Length);Answer
4
The number written as text has four digits.
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