What is the difference between string and StringBuilder?

C# Strings Basic Fresher1–2 Yrs Conceptual 1 min read

Quick Answer

string is immutable — every concatenation or modification allocates a new string object. StringBuilder is a mutable buffer; appends modify it in place (growing an internal array as needed). Use StringBuilder when building a string through many operations, especially in a loop; use string (and interpolation or string.Join) for a few, known concatenations.

A string in C# is immutable, so anything that looks like modifying it actually creates a new string. That's fine for a couple of concatenations — the compiler folds a + b + c into one call — but in a loop it's quadratic and hammers the garbage collector because every iteration allocates a new string. StringBuilder is a mutable buffer that appends in place and only resizes its internal array occasionally, so building a big string in a loop is linear. So: StringBuilder for loops and large generated text, plain interpolation or string.Join for a small fixed number of pieces.

Because strings are immutable, s += x inside a loop of 10,000 iterations creates ~10,000 intermediate strings and copies, which is O(n²) work and heavy GC pressure.

  • Use StringBuilder for loops, unknown numbers of parts, or building large text (reports, CSV, generated code).
  • Use plain concatenation / interpolation for a fixed small number of parts — the compiler optimises a + b + c into a single string.Concat.
  • Use string.Join for joining a collection with a separator.
  • Immutability also gives you thread-safety and lets the runtime intern string literals.

C# — building a string in a loop
// BAD: O(n^2), lots of garbage
var s = "";
foreach (var row in rows) s += row.ToCsvLine() + "\n";

// GOOD: O(n)
var sb = new StringBuilder();
foreach (var row in rows) sb.Append(row.ToCsvLine()).Append('\n');
var csv = sb.ToString();