EasyConcept

What is the difference between string and StringBuilder in C#?

Technology:
C#
Experience:
Intern,
Junior

Quick answer

A string is immutable, so every change creates a new string object, while StringBuilder is a mutable buffer that modifies its contents in place, making it much faster for repeated concatenation.

Detailed explanation

Each time you do s += "x" in a loop, the runtime allocates a new string and copies the old content, which is O(n squared) work overall and creates a lot of garbage. StringBuilder keeps an internal character buffer that grows as needed, so appending is cheap and you call ToString() once at the end.

For a handful of concatenations, a plain string or string interpolation is clearer and just as fast. Use StringBuilder when building text in a loop or from many pieces.

Example

csharp
var sb = new StringBuilder();
for (int i = 0; i < 10_000; i++)
{
    sb.Append(i).Append(',');
}
string result = sb.ToString();
  • C#Easy

    What is the difference between const and readonly in C#?

    A const is a compile-time constant that must be assigned where it is declared, while a readonly field can be assigned at declaration or in the constructor, so its value can be decided at runtime.

    Junior 路 Mid-level 路 Programming Fundamentals
  • C#Medium

    What is LINQ in C# and what is deferred execution?

    LINQ (Language Integrated Query) lets you query collections, databases and XML with a consistent syntax, and deferred execution means a query does not run when you define it but when you enumerate the results.

    Junior 路 Mid-level 路 Functions & Scope