String + versus StringBuilder benchmarks for 50K one char concatenations in .NET 7

I’m sure there’s still some junior .NET devs using + to concatenate large (usually an unknown) amounts of strings?

Look at that memory allocation 😲 …

Click on the image for a larger view in a new window.

Why such a big difference?

Well of course strings are immutable in .NET.

To quote Microsoft …

The String object is immutable. Every time you use one of the methods in the System.String class, you create a new string object in memory, which requires a new allocation of space for that new object. In situations where you need to perform repeated modifications to a string, the overhead associated with creating a new String object can be costly.

GitHub Gist to re-create

Leave a Reply

Your email address will not be published. Required fields are marked *