Friday, September 26, 2008

The Overuse of the StringBuilder class in .NET

So this friend of mine Adam wrote this post today. The main point of the post I love, as it correctly abstracts the creation of the query string behind a class and away from the rest of the code that is consuming the query results. Why I'm writing this post is that while his post was not directly having to do with the StringBuilder class, IMHO, he is displaying what I believe is indicative of the over zealous use of the StringBuilder class.

For the sake of convenience, this is how he wrote it:

private static string BuildDefaultViewQuery()
var builder = new StringBuilder();
builder.Append("<Eq><FieldRef Name='DefaultView' /><Value Type='Boolean'>");
return builder.ToString();

This is how I would have written the guts of this method:

private static string BuildDefaultViewQuery()
return String.Format(@"
<FieldRef Name='DefaultView' />
<Value Type='Boolean'>{1}</Value>
I just happen to think that there is too much "noise" when using a StringBuilder for this kind of stuff. Yes, if you're looping through a potentially large set of data and producing a potentially large string as a result, then by all means, use a StringBuilder, as that is what you should be doing. But if you're just building a relatively static string, with a handful of "variables" inserted into the string, use String.Format() in conjunction with a string that supports line breaks (i.e., using the @"" syntax). The resulting code is so much easier to read and understand what is really going on besides the building of a string.


David Stull said...

I believe String.Format() uses a StringBuilder internally. I agree that the String.Format() syntax is nicer.

BigJimInDC said...

I believe this web page covers this well enough from a performance point of view:

As my point, per the specific example, had nothing to do with performance-bound scenarios and everything to do with style in non-performance-bound scenarios, I'm not going to change my stance on this. Unless you're sitting in a loop concatenating strings, or concatenating relatively large strings (i.e., greater than a couple thousand characters), String.Format() is the way.