Will "the Mighty" Strohl

String Performance Benchmarks

I have a public tutorial document that I have just found out needs a little revisioning.  Generally, you do not ever want to put string objects together using the standard concatenation character such as "&" or "+". The problem lies in how the string is handled at runtime. 

For each concatenation character, a new string object is created in memory, and then the two string objects are put together.  It may not sound like it from this short description, but such practices can bring a busy application down to its knees in no time flat.

Generally, for smaller strings, you would never use the StringBuilder object.  In those cases, we use String.Concat or String.Format.  But which one is more efficient?

I decided to test this out in a console application.  I created two loops that each built a string using either the format or concat methods exclusively.  Here are the results...

First, I tried something small.  This is similar to what you might see on a single page load - if your web page does not havea whole lot of content.

Console Application

What you see above is nothing out of the ordinary.  The two strings are each built 15 times and then the loops quit, reporting the elapsed time it took to build each string.

Once we get to something like 45,000 iterations of the string build, we begin to see some impact where String.Format begins to under-perform by 100%.

Console Application

This behavior continues through 200,000 iterations.

Console Application

Now, when we bump the string build iterations to 2,000,000 the time it takes for the strings to build actually reverses!

Console Application

You can see in the above screenshot that the String.Concat method of building strings actually is over 150% slower now.  That is incredible?

What does this happen? I have no idea.  But realize this.  Unless you are working on a project where you have millions of string builds in a short time period, this final test is useless.  Informative, but useless. 

So which is faster?  String.Concat certainly appears to be the clear winner.  However, this is also a very simplified example of putting strings together. 

While in instances where there are only a couple of strings being put together at a time there appears to be no benefit either way, I must urge you to remember that even thousandths of a second add up.  In no time at all, you could wind up with an under performing application.

The bottom line is that you should perform this same testing yourself against your own application.

Technorati Tags: , ,

blog comments powered by Disqus