A string is immutable, so every change creates a new string object. A StringBuilder is mutable and appends into an internal buffer, so repeated changes avoid those extra objects.
Concatenating in a loop shows the cost. Each += on a string copies all the text built so far, so the total work grows with the square of the length. StringBuilder keeps one buffer and only reallocates when its capacity runs out.
Use string for a few concatenations, where the difference is too small to matter. Use StringBuilder when you build text in a loop or across many steps.
Immutability also makes a string safe to share across threads. A StringBuilder is not thread-safe, so one thread should own it.
// Inefficient - creates multiple string objects
string result = "";
for (int i = 0; i < 1000; i++)
{
result += i.ToString(); // Creates new string each time
}
// Efficient - uses internal buffer
StringBuilder sb = new StringBuilder();
for (int i = 0; i < 1000; i++)
{
sb.Append(i); // Modifies existing buffer
}
string result2 = sb.ToString();
This answer doesn't lend itself to a diagram - it reads best . No credits were charged.
Why there's no diagram: “”
The interactive diagram is below the answer - jump to diagram ↓ · Below it, the related concept . Jump to it ↓
The diagram below the answer is the concept . Jump to it ↓