StringBuilder vs. Concatenation

226 words.

Another in a series of random programming tips by Thomas Krehbiel, mostly to help me remember them in the future.

I was working on a project once and came across this VB.NET code:

Dim top as StringBuilder
top.Append("Content-Type: application/x-wmflatfile" + _
  Environment.NewLine + Environment.NewLine)
top.Append(...etc...)

With an exasperated sigh, I changed it to:

Dim top as StringBuilder
top.Append("Content-Type: application/x-wmflatfile")
top.Append(Environment.NewLine)
top.Append(Environment.NewLine)
top.Append(...etc...)

I don’t know about anyone else, but I was taught that StringBuilder was quicker than concatenation for manipulating strings, and given what I know about the inner workings of StringBuilder objects vs. String objects, that makes sense to me.

However, I found a discussion on the performance of StringBuilder vs. concatenation which partially discredits me by suggesting that straight concatenation is actually faster in some cases. They say that StringBuilder is always slower when you have to concatenate 3 or fewer strings.

I stick by my modification, however, because there were a number Appends, each with string concatenations in them. It seemed pointless to me to use string concatenation when there was already a StringBuilder object created, and the combination of string manipulation methods also appeared to indicate a fundamental lack of knowledge about the inner workings of object-oriented programming. In reality, the change had zero impact on the performance of the application. It just bugged me because of the principle of the thing.

Related

This page is a static archival copy of what was originally a WordPress post. It was converted from HTML to Markdown format before being built by Hugo. There may be formatting problems that I haven't addressed yet. There may be problems with missing or mangled images that I haven't fixed yet. There may have been comments on the original post, which I have archived, but I haven't quite worked out how to show them on the new site.

Sorry, new comments are disabled on older posts. This helps reduce spam. Active commenting almost always occurs within a day or two of new posts.