Strings versus StringBuilders In C#

As a C# Performance Architect, your job is to create solution architectures that provide the best possible performance for your business or organization. And to do your job well, you’ll need a solid understanding of basic C# code optimizations.

In this post, we’ll look at two ways to concatenate strings. Understanding the difference between these two methods will help you pick the correct strategy for every occasion.

Take a look at the following code.

static void Main(string[] args)
{
    string result = string.Empty;
    for (int i=0; i < SOME_LARGE_NUMBER; i++) {
        result += "*";
    }
}

I start with an empty string  result  and add an asterisk character to it in a loop. The loop itself repeats many times, leading to thousands or perhaps even millions of individual string concatenations.

But wait! There’s another way of doing this.

Check out the following code:

static void Main(string[] args)
{
    StringBuilder result = new StringBuilder();
    for (int i=0; i < SOME_LARGE_NUMBER; i++) {
        result.Append("*");
    }
}

So now I’m using a StringBuilder instead, and inside the loop I’m using the Append() method to add the asterisk.

Pretty much the same code, right? So which one do you think is faster?

I’ve coded a quick benchmark to compare the two parse methods. Take a look:

Did you see the results? The first benchmark used strings and performed 50,000 concatenations in half a second. The second benchmark used a StringBuilder instead, and it completed 100,000,000 concatenations in 0.45 seconds. The string code was a whopping 2000 times slower than the StringBuilder code!

That’s a massive difference. The reason is that strings are immutable. When you modify a string, the .NET framework creates an entirely new string on the heap and leaves the original unchanged. So my string benchmark code had to allocate and copy 50,000 strings on the heap. That really adds up.

Conversely, the StringBuilder class simply allocates a buffer in memory and writes data directly into it. This is much faster and makes StringBuilders ideally suited for building large strings.

You might be wondering if you should always use StringBuilders instead of strings, even when you’re only doing two or three additions? Should you chuck out all of your String.Format calls and replace everything with StringBuilders?

Well, check out the following comparison:

For up to 5 additions, using strings is actually faster. This is because there’s some overhead involved in setting up a new StringBuilder, and for a small number of additions the string class can still outperform the StringBuilder. But at 6 or more additions, the StringBuilder starts outperforming strings.

So here’s what you need to do:

  • For a small number of additions, stick to using strings.
  • When you’re doing more than 5 additions, use a StringBuilder instead

 

 

Would you like to know more? I’ve created a series of blog posts on C# performance optimization. Each post is based on content from my courses and from actual techniques I’ve used in the field.

Take a look: