Home
Blog
When to Use StringBuilder in C#
Updated
Dot Net Perls

When to Use StringBuilder in C#

It is common to need to append one string to another in C# programs. This is called concatenation. In languages where strings can be modified after being created, this is efficient—but in C#, strings are immutable and concatenation leads to a new string creation.

Creating too many new strings will cause excessive allocations and copying of memory. This can lead to big performance problems. StringBuilder can eliminate this problem by providing a buffer into which all the strings are copied, with fewer allocations.

We can use StringBuilder when:

We need to create a new string from many existing strings.
We want to append or concatenate two or more strings.

In the case of two strings, it can be faster just to concatenate the strings directly, but it is also acceptable to use StringBuilder. If further appends are needed, the StringBuilder will prevent future performance problems. So it is useful as a preventative measure against excess string copies.

Dot Net Perls is a collection of pages with code examples, which are updated to stay current. Programming is an art, and it can be learned from examples.
Donate to this site to help offset the costs of running the server. Sites like this will cease to exist if there is no financial support for them.
Sam Allen is passionate about computer languages, and he maintains 100% of the material available on this website. He hopes it makes the world a nicer place.
An RSS feed is available for this blog.
Home
Changes
© 2007-2025 Sam Allen