Should we always use StringBuilder in C#

I’ve seen developers use StringBuilder to concatenate 2 small strings in C# and I started thinking, are we so used to reaching for StringBuilder that we never stop and think, is this overkill? So I wanted to run some benchmarks and find the sweat spot in terms of speed and memory allocation where it makes sense to use StringBuilder instead of simple concatenation.

Lets start off with a very simple example.

Now ofcourse this is only doing one string operation by combining the 4 individual strings in one go, but it is some I see some developers doing. How does it fair in terms of bench marking.

The simple string concatenations is almost twice as fast and 1/3 the memory alloction.

Lets ramp it up so the simple concatenation is actually doing 4 operations.

Here we can see StringBuilder beings to outperform simple concatenation in terms of pure speed, but slightly higher memory allocation.

What happens if we make are strings much larger?

Interestingly StringBuilder is slower in this example and still has higher memory allocation.

What happens if we double our 4 small string concatenation operations to 8?

Here we are begining to see what we would expected, StringBuilder is out performing simple concatenation in terms of speed and memory allocation.

Lets check again with 12 string operations.

Again StringBuilder is outperforming simple concatenation.

Lets take it up to 100 concatenations

Here we really start to see the benefit of StringBuilder.

Summary

In my testing, StringBuilder didn’t really pay off until concatenating> 6 strings.

Comments

Leave a Reply

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