← Back to Blog
String vs StringBuilder in .NET: Practical Differences

String vs StringBuilder in .NET: Practical Differences

Working with text in .NET is simple on the surface, but performance depends heavily on whether you use string or StringBuilder. This is a focused comparison with concrete examples.

String is Immutable

A string cannot change once created. Any modification produces a new string object.

string s = "Hello";
s += " World"; // creates a new string in memory

If this happens many times, especially in loops, you create a lot of temporary objects and increase memory and GC pressure.

StringBuilder is Mutable

StringBuilder keeps an internal buffer that grows as needed. Appending text modifies the existing buffer instead of creating new objects.

var sb = new StringBuilder();
sb.Append("Hello");
sb.Append(" World");

This keeps memory usage stable even with many operations.

Performance Difference

Here is a common example that shows the difference.

Inefficient approach

string result = "";
for (int i = 0; i < 10000; i++)
    result += i;

Each iteration creates a new string. With 10,000 iterations, that means 10,000 allocations.

Efficient approach

var sb = new StringBuilder();
for (int i = 0; i < 10000; i++)
    sb.Append(i);

string result = sb.ToString();

Much fewer allocations and faster execution.

When to Use What

Use string when:

  • Text is small
  • Modifications are rare
  • Readability is more important
  • Concatenations are minimal
var msg = $"Hello {name}";

Use StringBuilder when:

  • You build text in loops
  • You append many segments
  • Generating logs, reports, SQL, HTML or JSON manually
  • Performance matters

Simple Rule

Up to a few concatenations: use string.
Repeated modifications or loops: use StringBuilder.

Summary

FeaturestringStringBuilder
MutabilityNoYes
Allocations on changeHighLow
Good forSmall, simple textLarge or repeated operations
Typical useMessages, formattingLogs, builders, loops