Since there’s been so many amazing performance improvements in .NET 6 I thought it would be fun to compare different .NET string concatenation approaches to see which is the best performing and which is the most memory efficient.
Below are benchmarks taken using BenchmarkDotNet for a simple scenario of just adding 4 strings with spacers and a scenario where we are adding a lot of variable width strings. I’ve included .NET Core 3.1 and .NET 5 benchmarks for reference too.
Benchmarks were taken on a 16GB ram Azure VM… the .NET 6 version was RC2…
The benchmarks show results in nanoseconds and microseconds which are tiny slices of time.
Remember don’t micro-optimise if you don’t need to… if you’re only doing simple .NET string concatenation and not doing it in a hot loop… as always focus on whichever approach is MOST READABLE FIRST… BUT if you have a need to optimise to this level the below benchmarks should guide you.
Concatenating a small amount of strings
For the simple scenario of concatenating just a few strings String.Join is clearly the fastest, while string interpolation is super efficient in terms of memory allocation.
Note the significant performance increases between .NET 5 and .NET 6 for String.Format, string interpolation and String.Join. We can also see that memory allocation in .NET 6 for the string interpolation approach is less that half of what it was in .NET 5… AWESOME!!!
Concatenating a large amount of strings from an array or list
When we are concatenating a large amount of random width strings we know the plain string concatenation (+=) approach is not ideal as its performance and memory efficiency is quite poor.
Quite often we first hear about StringBuilder as a more performant alternative to plain string concat and indeed its performance is better than plain string concatenation. For scenarios however where we have a known set of strings in an array for example StringBuilder is not the best option as other approaches such as using String.Concat or String.Join are more suited. This is because these methods can determine final string length ahead of time by examining the collection.
In the below benchmarks where I’m appending 200 strings from a string array we can see that using String.Concat is the fastest .NET string concatenation approach, with String.Join not far behind. Note the very high memory allocation for the plain string concatenation approach.
I’ve included StringBuilder benchmarks for reference but note the best use case for StringBuilder is for when we do not know the final length of the string and/or how many append operations we will have to do.
Recreating the benchmarks
If you’d like to recreate the .NET string concatenation benchmarks shown above to see if you get similar results the classes and random string file are below…