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:
string
from many existing 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.