Most efficient way to concatenate strings?


What's the most efficient way to concatenate strings?

9/18/2016 12:41:19 AM

Accepted Answer

The StringBuilder.Append() method is much better than using the + operator. But I've found that, when executing 1000 concatenations or less, String.Join() is even more efficient than StringBuilder.

StringBuilder sb = new StringBuilder();

The only problem with String.Join is that you have to concatenate the strings with a common delimiter. (Edit:) as @ryanversaw pointed out, you can make the delimiter string.Empty.

string key = String.Join("_", new String[] 
{ "Customers_Contacts", customerID, database, SessionID });
10/12/2017 6:59:16 AM

Rico Mariani, the .NET Performance guru, had an article on this very subject. It's not as simple as one might suspect. The basic advice is this:

If your pattern looks like:

x = f1(...) + f2(...) + f3(...) + f4(...)

that's one concat and it's zippy, StringBuilder probably won't help.

If your pattern looks like:

if (...) x += f1(...)
if (...) x += f2(...)
if (...) x += f3(...)
if (...) x += f4(...)

then you probably want StringBuilder.

Yet another article to support this claim comes from Eric Lippert where he describes the optimizations performed on one line + concatenations in a detailed manner.

Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow