2

String Performance: Concatenating Strings – dotNetTips.com

 2 years ago
source link: https://dotnettips.wordpress.com/2021/11/04/string-performance-concatenating/
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client

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.

Tagged Code Performance, Strings

I live in San Diego, Ca USA View all posts by dotNetDave


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK