C# Interview Question #119

What is StringBuilder, and when should it be used?

Concurrency, Performance & Design Senior Advanced

Quick Interview Answer

StringBuilder is a mutable buffer designed for efficiently constructing strings through many modifications or concatenations.

Detailed Explanation

StringBuilder is a mutable buffer designed for efficiently constructing strings through many modifications or concatenations.

Strings are immutable, so repeated concatenation in a large loop can create many temporary string objects. StringBuilder can reduce those allocations.

For a small number of concatenations, normal interpolation or + is usually simpler and sufficiently efficient. StringBuilder is most useful when building larger strings incrementally or inside substantial loops.

Code Example

var builder = new StringBuilder();

for (int i = 1; i <= 1000; i++)
{
    builder.Append("Item ");
    builder.AppendLine(i.ToString());
}

string result = builder.ToString();