Skip to content
Tutorials Center
My learning

Topics

Lesson 30 of 182 ยท Strings

StringBuilder

Learn why repeated string concatenation is slow and how StringBuilder fixes it - Append, Insert, Remove, capacity, AppendJoin, chunks, plus string.Concat, string.Join and string.Create.

Because strings are immutable, every + creates a brand-new string and copies the old characters into it. For a handful of concatenations that is invisible. Inside a loop that runs ten thousand times it becomes a real cost in time and memory. StringBuilder is the standard answer: a mutable buffer of characters that grows as you append and produces one string at the end.

In this lesson you will measure the problem instead of just believing it, learn the StringBuilder API, understand capacity and chunking, and see the cases where you do not need a builder at all.

The cost of concatenation in a loop

Suppose you build a text of 5,000 short lines with +=. Each iteration allocates a new string as long as everything so far, and the previous one becomes garbage. The total number of characters copied grows with the square of the line count.

We can measure the allocated bytes with GC.GetAllocatedBytesForCurrentThread(). Exact numbers differ between machines and runtime builds, so the program compares them instead of relying on exact values.

C# Counting allocations

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

The += version allocates well over 100 megabytes to produce a text of about 49,000 characters (roughly 100 KB), because each of the 5,000 iterations copies everything built so far. The builder produces the same text with less than a megabyte of allocations: the buffer chunks plus the final string. That is the whole reason StringBuilder exists.

Do not use a builder for a fixed, small number of concatenations such as first + " " + last. The compiler turns that into a single string.Concat call that allocates exactly one result string, which is faster than creating a builder.

The StringBuilder basics

Create one with new StringBuilder() (optionally with starting text or a capacity), call Append many times, and finish with ToString(). Most methods return the builder itself, so you can chain calls.

C# Append, AppendLine and chaining

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

Append has overloads for every primitive type, so numbers are converted without you creating a temporary string. AppendLine adds Environment.NewLine, which is \n on Linux and macOS and \r\n on Windows. Passing an interpolated string directly to Append is efficient too: StringBuilder has its own interpolated string handler, so no intermediate string is created (see Interpolation and Formatting).

Insert, Remove, Replace and indexing

Unlike a string, a builder can be edited in place.

C# Editing in place

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

Setting Length smaller truncates the content; setting it larger pads with '\0' characters. Clear() resets the length to zero but keeps the allocated capacity, which makes a builder reusable in a loop. Be aware that Insert and Remove in the middle of a large builder shift the characters after the position, so they are O(n) per call; if you do many of them, think about building the text in the right order instead.

Capacity: avoiding reallocation

A builder owns a buffer. Length is how many characters you have written; Capacity is how many fit before the buffer must grow. When it is full, the builder adds a new chunk, whose size doubles up to a limit, instead of copying everything.

C# Watching the capacity

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

If you can estimate the final size, pass it to the constructor. You save the intermediate growth steps. A rough guess is better than none; an over-estimate wastes only memory. There is also EnsureCapacity(n) for builders you already hold.

Chunks: how a builder is built inside

Since .NET Framework 4.0 a StringBuilder is not one big array. It is a linked list of chunks, each a char[]. Appending fills the last chunk; when it is full a new, larger chunk is linked in. That is why appending never copies the existing text, and why ToString() has to copy every chunk into one final string once.

You can look at the chunks with GetChunks(), which returns a ChunkEnumerator over ReadOnlyMemory<char> pieces (.NET Core 3.0 and later). This is the way to write a huge builder to a file or socket without ever creating the whole string.

C# Reading chunks without building one huge string

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

One consequence: the indexer sb[i] must walk the chunk list, so random access into a very large, many-chunk builder is slower than for a plain string. Iterate with GetChunks() or call ToString() once if you need to read a lot.

Joining with AppendJoin

AppendJoin(separator, items) appends a sequence with a separator between the elements, without the trailing-separator problem of hand-written loops (.NET Core 2.0 and later).

C# AppendJoin and a SQL-style list

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

(The text above only illustrates joining; never build real SQL from user input this way.)

Alternatives that need no StringBuilder

A builder is the right tool when the number of pieces is unknown or large. For other situations, simpler tools are better and often faster.

string.Concat and string.Join. When the pieces are already in a collection, one call does the whole job with a single allocation of the exact size.

Interpolation. For a fixed template, $"{a}-{b}-{c}" is compiled to efficient code and is the most readable.

string.Create. When you know the exact final length and want to fill the characters yourself, string.Create(length, state, action) gives you a span over the new string's memory before it is published. That is the allocation-optimal way to build a string: one allocation, no copy.

C# Concat, Join and string.Create

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

Another special case is a small, temporary buffer: for short strings Span<char> on the stack with stackalloc, or pooled ArrayPool<char>, avoid allocations entirely. Those techniques come in Spans and Memory.

Guidelines

  • Many concatenations in a loop, or unknown count: use StringBuilder.
  • A few known pieces: use + or interpolation.
  • A collection of pieces: string.Join or string.Concat.
  • Reuse a builder in a hot path by calling Clear() instead of creating a new one.
  • A StringBuilder is not thread-safe. Give each thread its own.
  • Call ToString() once at the end; each call copies the content.
  • Do not use a builder to compare or search text; ToString() first, or work with the chunk spans.

Measure before optimizing. For text under a few hundred characters, readability beats micro-optimization. The loop-concatenation problem is real, but only when the loop is large.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. Why is s += x inside a long loop slow?

    Strings are immutable, so every concatenation builds a new string. Total copying grows quadratically with the number of iterations.
  2. 2. What does Capacity of a StringBuilder describe?

    Length is how many characters you have appended; Capacity is how many fit without growing.
  3. 3. Which is the best choice for first + " " + last?

    A fixed small number of pieces compiles to one string.Concat call, which allocates exactly one string.
  4. 4. What is string.Create mainly used for?

    It hands you a span over the new string's memory so you can write the characters directly before the string becomes visible.
  5. 5. What does Clear() do to a StringBuilder?

    Clear resets Length to zero. The memory is retained, which is handy when reusing a builder.

Summary

  • String + in a loop copies everything each time; StringBuilder appends into a growing buffer and creates one string at the end.
  • Use Append, AppendLine, AppendJoin, Insert, Remove, Replace; the indexer can read and write.
  • Capacity can be pre-sized; internally a builder is a list of chunks you can read with GetChunks().
  • For few or known pieces, prefer +, interpolation, string.Join/Concat; for exact-size construction use string.Create.
  • A builder is not thread-safe; call ToString() once.

Next: Raw, Verbatim and UTF-8 String Literals