Tip of the Day #8 (string performance)

Concatenating strings in .NET can be very easy. There is the overloaded + operator that makes stringA + stringB + stringC statements very easy to write. But, it isn’t very performant. The reason is that strings are immutable, and concatenating strings in this way causes lots of short-lived objects to be created and thrown away, which in turn causes the garbage collector to run frequently.

There are two better ways in .NET to concatenate strings. One is to use the string.Concat() method. The other is to use the StringBuilder class. They both perform better than adding strings together, but you still have to know when to use each.

According to this article on “Performance considerations for strings in C#string.Concat() is good up to 600 strings. But, only if you have 600 strings to concatenate in a single statement. StringBuilder is better if you have more than 600 strings to concatenate, but you can do so over multiple statements. In reality, I think the benefits of appending strings over multiple statements with StringBuilder will work out better even with much less than 600 strings because to get the performance out of string.Concat() you’ll have to perform some form of setup operation to line all those strings up – and that will take time.

So, today’s tip is don’t use the plus operator to combine strings except in quick / throw-away applications. Use string.Concat() or StringBuilder instead.

2 Comments

  1. Mike Dimmick says:

    Wow, I didn’t think you’d be caught out by this. The C# and VB compilers will turn repeated uses of + *in the same expression* into a call to an overload of string.Concat.Just looking in Reflector’s C# or VB view won’t reveal this as it converts the compiled code back to the sequence of + operations. You have to look at the IL.Now, if you’re doing it in a loop – for example you don’t know how many strings you have – you should use StringBuilder.

  2. My example was probably bad. I should have used a += b; a += c;as the linked article did.

Leave a Reply to Colin Angus Mackay Cancel reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s