Do Not Use the StringBuilder

I know there are plenty of people out there that will disagree with me, but I urge you to not use the .NET StringBuilder class in 99% of the cases you would be tempted or recommended to do so.  Here is why:

 The StringBuilder class does perform better than basic string concatenation.  However, it is really only noticable with ridiculous string lengths.  For example, if you are concatenating a SQL statement together for a statement that has less than 100 columns, the difference will be negligible.  Slamming 10,000 strings puts StringBuilder as the clear winner in time as it will shave about 2 tenths of a second off of your processing time.

Testing In Progress

I ran some tests, and comparing a basic concatenation to using a string builder to slam together 100 “A” characters is a wash.  Sometimes the StringBuilder even took longer.  At 1000 characters, StringBuilder was a slight winner.  Of course this amounted to about 20 milliseconds on average.  Unless you are doing a lot of concatenation, this won’t really be a noticable difference… and we are already talking about 1000 operations!

Below are the results of my test (click on thumbnail) that were not posted on my original rant, but have since been added to this post.  You can see the strings of varying lengths I used as well as the number of concatenation operations that were performed on each.  The “Total String Length” column represents the overall lentgh of the resulting string after all operations are complete.

The Results of My Tests

As you can see, nothing short of  millions of resulting characters or tens of thousands of concatenation operations ends up in response time that is over 1 second.  Looking at a typical operation in my world such as concatenating a SQL statement together, we would be dealing with something like rows 9 and 10 of the above table.  These tests took the string “AND COLUMN1 = ‘VALUE’” and concatenated it together 1,000 times.  Although this would still be a ridiculously long SQL statement (and probably perform horribly :)), the difference between using a StringBuilder (193 ms) and simple concatenation (214 ms) is only 41 milliseconds difference.  Yes, I realize that is about 20%, but again, if you are doing this concatenation many times, you may need to write your own custom object to meet your true needs.  Another interesting find is that the # of operations seems to have a much bigger impact than the overall length of the string itself.

Yes, it is terrific that somebody at Microsoft realized working with a collection (string) of hundreds of thousands of members (characters) will not perform will if it is not indexed.  No kidding!  But who in their right mind will be dealing with strings of 500,000+ characters?  If you are doing that, then you probably need to rethink your approach to solving the problem at hand.

 Because of the added complexity, additional lines of code, developer ramp-up possibility (for those not exposed to the class or .NET) and risk of change in future versions of .NET, I say you should not use the StringBuilder class… unless, of course, you find yourself needing to deal with that all to common million character string🙂

6 Responses

  1. I know there are plenty of people out there that will disagree with me

    If we are to call ourselves “computer scientists” people will investigate your assertion on their own. I myself am off to slam some strings together in the controlled environment of my Sunday morning coffee and SharpDevelop. Thanks for the tip; I will experiment … *insert maniacal coder laugh*

    Kindness (which should be immutable!)

    Dan

  2. Here is another interesting post on the subject:

    http://www.daniweb.com/forums/thread1626.html

  3. Did you try the StringBuilder(int capacity) constructor? It’s the whole point of the stringbuilder and it blazes past the String class after just a few adds…

  4. I should probably qualify my initial recommendation (and maybe backpeddle just a little bit :)) to not use it and note that this is for general applications of simple string use. There are indeed many good reasons to use a StringBuilder. Any application that is doing string concatenation inside of a loop, for example, is almost certainly a candidate for using a StringBuilder. Using a string builder to parse together an error message, however, is not.

    Put another way, if you are wondering whether or not to use one, my guess is you don’t need to. If you know that you have performance issues, and they may be related to string concatenation then that is an easy call. In this case, educated by this and other great posts out there you’ll know that a StringBuilder is the right choice.

    Thanks for the post on that angle.

  5. I haven’t profiled it, but intuitively, I’m betting that StringBuilder uses less memory than String concatenations (I’m talking in terms of total paging and GC’ing, not how much memory is held by the backing buffer of a String or StringBuffer object at a given time, which should be nearly identical sans the bookkeeping overhead). I say this because of the amount of memory that is required to instantiate a new String object once per concatenation, versus single object instantiation and preallocation with StringBuilder (and even when it overflows, only the backing buffer is reallocated, no new object is created). Also, on memory-constrained systems, GC’ing a bunch of large, temporary string objects could in fact cause a noticable slowdown (which may not be apparent on a system with lots of free memory in which the GC may not even be triggered during a benchmark). Bottom line, listen to Microsoft: “when performance is important, you should always use the StringBuilder class to concatenate strings.” (cited from “How to: Concatenate Multiple Strings” on MSDN). But as you say, performance probably isn’t important when you’re trying to do “OOPS: Got a ” + err.Message.🙂

  6. Ack. Java on the brain… StringBuffer=StringBuilder

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: