Main menu:

Site search

Categories

Archive

High Performance String Concatenation in .NET

Have you ever spent time thinking about how string concatenation works in .NET? Probably not (and I can’t blame you for this) but if you were wondering then please continue.

If you remember way back to your first programming class, you probably learned about how strings work and how they’re not really a primitive type (even though they masquerade as one). Strings are really just collections of characters. Let’s skip Computer Science One for right now and look more closely at how .NET handles string concatenation. If this is the first time you’ve heard that a string is not a primitive type (it’s just a collection of characters, blah, blah blah), then by all means please search on Google for more lengthy explanations.

There are three common ways to concatenate a string in C#:

  1. The overloaded + (plus) operator
  2. String formatters
  3. StringBuilder


I wanted to see which one was really more efficient within the .NET Framework so I created three versions of a console application that built a simple string.

The first version was using the + (plus) operator. Here is the C# code:

This is the generated IL code for the + (plus) operator concatenation:

The second version was using a string formatter. Here is the C# code:

This is the generated IL code for the string formatter concatenation:

The third version was using a StringBuilder. Here is the C# code:

This is the generated IL code for the StringBuilder concatenation:

As you can see, the + (plus) operator generates a almost twice as much IL code to do the same thing as a string formatter! Do that a few thousand or so times and there could be a noticeable performance issue in your code. It is also slower to use the + (plus) operator for string concatenation. StringBuilder is a special case. While it generates more IL code than a string formatter, it is a lot faster.

So, what does this all mean?

For everyday string concatenation of two strings use either the + (plus) operator or a string formatter. Once you start concatenating more than two strings, you should use a string formatter. If you find yourself concatenating large amounts of string data then you should be using a StringBuilder for optimal performance.

Write a comment