Stringbuilder Append vs. AppendFormat

My last post was on the merits of using a StringBuilder vs. concatenating strings. For those of you who are really worried about performance, there is another thing to think about when using the StringBuilder – using Append vs. AppendFormat.

AppendFormat is sort-of handy. You can build up a string with replaced values in the middle:


StringBuilder sb = new StringBuilder();
sb.AppendFormat("The field {0} has the value {1}",strField,nValue);

However, you should be aware that this is significantly slower than building the string in pieces:


StringBuilder sb = new StringBuilder();
sb.Append("The field ");
sb.Append(strField);
sb.Append(" has the value ");
sb.Append(nValue.ToString());

It has been a while since I tested this, but as I recall, the separate appends are as much as 10 times faster than using the format command. This sort of makes sense, given that the AppendFormat has to worry about parsing the string.

As before, though, you should only really worry about this if performance is a really big issue. Most of the time, this simply is not the case. In fact, my next post may well be a screed on optimization.

And one more thing to worry about – the second approach is awful for strings that need to be localized. Sentence structure is different in other languages, and this will just plain not work. However, if you are building SQL or HTML or something like that, it is definitely something to think about.

Update: Tim pointed out that there is a practical upper limit to the StringBuilder. If you are working with strings around or over 256K, you should probably consider using streams (or reconsider your design!).

Technorati Tags:

Trackback URL for this post:

http://www.exotribe.com/trackback/28