Nov.16

C# String Performance

In my last post, I talked a bit about JavaScript performance specifically around For loops. Today’s topic is also performance related but specifically around building strings in C# in loops.

I think every programmer has had occasion to build quite large strings at runtime. Typically, however, string operations can cost you a lot in performance. I had run into this issue recently. I had started out building a large string with just simple concatenation like so:

string MyString = string.Empty;

for (int i = 0; i < 1000; i++)
{
    MyString += " This is an addition to MyString " + (i + 500).ToString() + " Some more addition to MyString";
}

We’ve all seen and used an approach similar to this. It’s easy to read and understand (generally). However, this little sample is really inefficient. It took 237 milliseconds on my machine. Hmm, maybe not so good.

Let’s try another way:

StringBuilder MyStringBuilder = new StringBuilder();

for (int i = 0; i < 1000; i++)
{
    MyStringBuilder.Append(" This is an addition to MyString " + (i + 500).ToString() + " Some more addition to MyString");
}
MyStringBuilder.ToString();

This approach only took 1.9 milliseconds! That’s a huge difference if you’re trying to shave your page load time down.

So what if we increase the upper bounds to say 10,000?

String Concatenation: 24,371 Milliseconds (24 Seconds)
String Builder: 29 Milliseconds (0.029 Seconds)

Now that’s a huge difference! You’d better believe that would make a difference in response time!

The big reason for the difference is that the string is being build in a loop. If you had a one-off string to build, you may not see that big of a difference. But if you using a loop, you’ll be much better off using String Builder!

Programming,Performance
Share this Story:
  • facebook
  • twitter
  • gplus

About Jeremy Foltz

Leave a comment

Comment