String Performance: Concatenating Strings

There are several ways to concatenate strings together in .NET. I would say most developers would do it like this.

string result = "David" + "McCarter";

You can also use string.Concat() like this:

string result = string.Concat("David", "McCarter");

You can also use string.Join() like this:

string result = string.Join(string.Empty, "David", "McCarter");

Combining Many Strings

Before we talk about the rest of this section, I must stop and remind you that strings in .NET are immutable. Because of this, combining multiple strings together could cause a performance and memory issue. I see developers doing this in their code often, even for building large SQL queries (which could also be a security issue). 

To benchmark the performance, I am looping through a string array to concatenate the strings. Here is an example.

var result = string.Empty;

for (int count = 0; count < stringArray.Length; count++)
{
   result += stringArray[count];
}

Benchmark Results

Let’s look at the performance of these three methods of combining strings from a string array with different word counts. As you might suspect, using += to concatenate strings for this benchmark allocates a lot more memory than the other two methods.

Combine Strings Chart

Allocations

There is a very big difference with the allocations for these three benchmark tests.

  • += is 1,848 to 15,039,946 bytes
  • Concat() is 400 to 30,096 bytes
  • Join() is 400 to 3096 bytes

My recommendation is to use Concat() since it is more performant if you don’t need to separate the strings with a character. If you do, then use string.Join(). I’ve been warning software engineers for a very long time about the performance and memory issues when using +=!

Pick up any books by David McCarter by going to Amazon.com: http://bit.ly/RockYourCodeBooks

© The information in this article is copywritten and cannot be preproduced in any way without express permission from David McCarter.


The benchmark results in this article are only for your reference. Your results will be different, so make sure to benchmark your code using Benchmarkdotnet.

2 thoughts on “String Performance: Concatenating Strings

  1. Curious that you did not benchmark StringBuilder as it is usually the recommended approach for multiple appends/concatentations…..

Leave a Reply

Please log in using one of these methods to post your comment:

WordPress.com Logo

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

Google photo

You are commenting using your Google 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

This site uses Akismet to reduce spam. Learn how your comment data is processed.