What is the difference between string and StringBuilder in C#?
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.
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.
var sb = new StringBuilder();
for (int i = 0; i < 10_000; i++)
{
sb.Append(i).Append(',');
}
string result = sb.ToString();