skip to content

In .NET, what does passing a capacity to `new StringBuilder(int)` save, given that a full StringBuilder grows by adding chunks?

level: middleimportance: should knowfreq 40%

answer

  1. room, not a limit
  2. sixteen chars by default
  3. linked chunks, no recopy
  4. 8,000-char chunk cap
  5. one chunk reads fastest

basics

~20 s

A StringBuilder starts with 16 chars of room; when full it links a new chunk sized to the current length (at most 8,000) or the request if larger, without copying old text. A right-sized capacity gives one buffer, no slack and a single-chunk ToString.

solid answer

~50 s

`Capacity` is how many characters the builder can hold before it must allocate again; it is not a limit. The limit is `MaxCapacity`, `int.MaxValue` by default, and only exceeding it throws `ArgumentOutOfRangeException`. A parameterless `StringBuilder` starts at 16. When an `Append` does not fit, the builder fills what room is left and links a new chunk of `max(needed, min(Length, 8000))` characters behind the old one; existing text stays where it is, so capacity roughly doubles while it is small and then grows 8,000 characters at a time, keeping each array on the small object heap. Passing a good estimate to `new StringBuilder(int)` therefore saves less than it would for a doubling-and-copying buffer: you avoid the chunk objects, their unused slack and the per-chunk work in `ToString()` and the indexer. In a 50,000-character test that was 200,096 bytes allocated pre-sized against 213,560 grown. The big win is using a builder at all.

code

csharp · 20 lines
csharp
using System.Text;

var sb = new StringBuilder();
Console.WriteLine($"empty: Capacity={sb.Capacity}, MaxCapacity={sb.MaxCapacity}");
sb.Append(new string('a', 17));
Console.WriteLine($"17 chars: Capacity={sb.Capacity}");

var sized = new StringBuilder(capacity: 100);
sized.Append(new string('b', 101));               // capacity is room, not a limit
Console.WriteLine($"101 chars in a 100-capacity builder: Capacity={sized.Capacity}");

var report = new StringBuilder();
for (int i = 0; i < 5000; i++) report.Append("0123456789");
Console.WriteLine($"50,000 chars: Capacity={report.Capacity}");
report.Clear();
Console.WriteLine($"after Clear: Length={report.Length}, Capacity={report.Capacity}");

var capped = new StringBuilder(capacity: 4, maxCapacity: 8);
try { capped.Append("123456789"); }
catch (ArgumentOutOfRangeException) { Console.WriteLine("past MaxCapacity: ArgumentOutOfRangeException"); }

go deeper

for a junior

Know that the default capacity is 16, that capacity is starting room rather than a limit, and that the builder grows on its own when you append more.

for a middle

Explain chunked growth: a new chunk sized to the current length, at most 8,000 chars, or to the request if larger, linked without copying old text, then ToString copying every chunk once.

for a senior

Judge when sizing matters: known output sizes, hot paths and reused builders benefit; unknown sizes do not need a guess, and huge over-estimates or retained builders waste memory.

for a principal

Weigh guidance against evidence: pre-sizing is a modest, measurable gain, so a team rule should favour StringBuilder or string.Join over += first and size only where profiles show it pays.

## Capacity is room, not a limit Three numbers describe a `System.Text.StringBuilder`, and they are easy to mix up: | Property | Meaning | Default | |---|---|---| | `Length` | characters currently in the builder | 0 | | `Capacity` | characters it can hold before allocating again | 16 for `new StringBuilder()` | | `MaxCapacity` | hard upper bound on `Length` | `int.MaxValue` | `new StringBuilder(100)` sets the initial **capacity**, not a maximum. Appending a 101st character simply grows the builder. Only `new StringBuilder(capacity, maxCapacity)` sets a ceiling, and an append past it throws `ArgumentOutOfRangeException`. Setting `Capacity` below the current `Length` throws the same exception. ## How a full builder grows In current .NET, a `StringBuilder` is a linked list of **chunks**, each with its own `char[]`. The runtime source handles a full builder like this: 1. `Append` copies as many characters as fit into the current chunk's spare room. 2. For the rest, it allocates a new array of `Math.Max(minBlockCharCount, Math.Min(Length, MaxChunkSize))` characters, where `MaxChunkSize` is 8,000. 3. It moves the old chunk's state behind the new one with a few reference updates; **no character is copied**. 4. The remaining characters go into the new chunk. While the builder is shorter than 8,000 characters, each new chunk is about as large as everything so far, so capacity roughly doubles: 16, 32, 64. After that, chunks stay at 8,000 characters (16,000 bytes), which the source comments say keeps them off the large object heap. A single large `Append` is the exception: the new chunk is at least as big as what is needed, so appending 20,000 characters to a 17-character builder creates one chunk of 19,985 characters, enough for the rest. The docs page on using `StringBuilder` still describes capacity as a maximum that doubles when reached; the runtime source and a run on .NET 10 show the chunked behaviour above. ## What a capacity saves Because growth never recopies old text, appending without a capacity is still linear overall. Pre-sizing saves smaller things: - **Chunk objects and slack:** every chunk is an extra builder object plus an array, and the last one is usually part empty. - **`ToString()` work:** it walks every chunk and copies each into the new string; one chunk means one contiguous copy. - **Indexer and `Insert` cost:** `sb[i]` starts at the newest chunk and walks back until it finds the one holding index `i`, so random access slows as chunks pile up. - **Measured:** 50,000 characters appended in ten-character pieces allocated 200,096 bytes with `new StringBuilder(50_000)` and 213,560 bytes without, both including the final string. A generous over-estimate is not free either: the constructor allocates the full array immediately, so a 1,000,000 guess for a 2,000-character result wastes about 2 MB per builder. ## Reuse and Clear `Clear()` sets `Length` to 0 and keeps the capacity; in the test, a builder that had grown to 56,192 characters still reported that capacity after `Clear()`. On a multi-chunk builder the runtime keeps one array large enough for the old content, so a builder reused for similar-sized output stops growing after the first round. The flip side is that a long-lived builder that once held a huge report keeps that memory until it is dropped. ## Picking a number - **You know the size:** the CSV export knows its row count and a typical row length, so `new StringBuilder(rows * 32)` is a cheap, honest estimate. - **You do not know it:** skip the capacity; chunked growth is already linear. - **Many small builders in a hot path:** cache and reuse one per thread or per operation, or build into a span with the low-allocation APIs covered elsewhere. - **Tiny appends:** `Append(char)` and the typed overloads such as `Append(int)` avoid creating a temporary string; analyzer rules CA1834 and CA1830 point these out. The interview summary: capacity is initial room, growth links chunks instead of copying, so a capacity trims allocations and speeds `ToString` modestly rather than rescuing an algorithm.

  • Why does `sb[i]` get slower on a builder that grew without a capacity?
    The indexer starts at the newest chunk and walks back through the earlier chunks until it reaches the one containing index i, so on a builder with hundreds of chunks a single lookup can walk hundreds of links. A builder sized up front has one chunk, so the lookup is immediate. Code that reads characters back often should call `ToString()` once and index the string.
  • Which analyzers point out wasteful StringBuilder calls?
    CA1834 suggests `Append(char)` instead of a one-character string such as `sb.Append(",")`, and CA1830 suggests the typed overloads such as `Append(int)` instead of `Append(x.ToString())`. In .NET 10 both are enabled only as suggestions, so they show in the editor rather than failing the build unless a team raises their severity.

A StringBuilder is a ring binder: when it fills you clip in a new section instead of recopying every page into a bigger binder, and ToString photocopies all sections once into a bound book. A capacity just means buying a binder thick enough from the start.

  • Capacity is the maximum number of characters a StringBuilder can hold.
  • A full StringBuilder doubles one array and copies every character, like List<T>.
  • Without an initial capacity, StringBuilder appends are quadratic, just like += on strings.
  • Clear() releases the builder's buffers back to the runtime.
  • Passing a huge over-estimate as capacity costs nothing.