A C# string cannot be changed after it is created. Every time you write s = s + "x", a brand new string is allocated and the old one is thrown away. In a loop that runs thousands of times, this creates a lot of garbage and gets slow.
StringBuilder keeps an internal buffer and appends into it, so building a long string in a loop is much cheaper.
It does not matter in every case:
Joining a few strings once is fine with +, string interpolation or string.Concat. The compiler optimises many of these.
For a list of items, string.Join(", ", items) is clearer and fast.
Use StringBuilder when you append in a loop or build large text, such as a report or CSV.
Do not rewrite readable code for a loop of ten items. Use StringBuilder where the loop is big.
Markdown for AI
A clean, structured version of this page for AI assistants and LLMs.
We use cookies to ensure you have the best browsing experience on our website. By using our site, you
acknowledge that you have read and understood our
Cookie Policy &
Privacy Policy.
A C# string cannot be changed after it is created. Every time you write
s = s + "x", a brand new string is allocated and the old one is thrown away. In a loop that runs thousands of times, this creates a lot of garbage and gets slow.StringBuilder keeps an internal buffer and appends into it, so building a long string in a loop is much cheaper.
It does not matter in every case:
string.Join(", ", items)is clearer and fast.Do not rewrite readable code for a loop of ten items. Use StringBuilder where the loop is big.