C# – String.Concat vs String.Join

I had a quick Google search for a comparison between string.concat and string.join, but I couldn’t find anything.

Say you want to construct the sentence “The quick brown fox jumps over the lazy dog”

This is comprised of 9 words, 8 spaces.

Using string.concat:

Using string.join

With String.concat, we must explicitly add the separator (in our case, space) between each string.

String.join however, allows us to specify the separator as the first parameter.

Performance

I wrote a small benchmark test on the two (see bottom of this post for code)

We can see string.join consistently performs better

string concat vs string join

Benchmark Code:

Note – This is available on GitHub – http://github.com/alexjamesbrown/StringConcatVsStringJoin

 


Update – StringBuilder.Append

In the comments, Dejan Stojanović put together a similar test using StringBuilder.Append – with similar, and sometimes slightly better results!

With stringbuilder.append

See this commit for the update

2207 Words
3423 Views