String concatenation - + vs StringBuilder

Countless times I've read that the when doing string concatenation, the StringBuilder class is more efficient than the String "+" operator. I pretty much just accepted that advice until a couple of days ago. But after poking around a bit, it now looks like there's some simple and common cases where in fact the opposite is true.

I got started on this because the existence of the String.Concat method finally entered my consciousness. I'm sure I've seen it before, but I never gave it much thought. Between "+" and StringBuilder, I never had much reason to, I guess. And I never see it used in sample code. When I finally grokked it's existence, I did a little Reflector'ing to look at the method's implementation (the Rotor source works just as well). Lo and behold, the Concat methods that take String arguments use what look to be efficient internal string allocation and copy methods to build up the concatenated string. There are Concat overloads for up to 4 string arguments, so I figured for simple cases I'll would just use String.Concat.

But it got even better. I found this interesting article, which talks about the internals of Strings in the .NET framework. It points out that the compiler converts string operator + calls of up to 4 arguments to a call to String.Concat. So a + b +c gets converted into String.Concat(a, b, c), which avoids the creation intermediate string objects.

With my curiosity piqued, I ran a very quick-and-dirty (and decidedly unscientific) test of 10,000 calls to "a + b + c" vs 10,000 equivalent StringBuilder calls. And in fact, a + b + c was faster. Now, I'm not really that worried about the relative performance of the two methods  - we're talking a few ticks here. But since the + operator (and even String.Concat) can be much more convenient to use than StringBuilder for quick and dirty string concatenation, I'm quite happy that I can use it without worrying about horrible inefficiencies. Obviously if you're building up giant XML strings, StringBuilder is the way to go. But if you're combining 4 or fewer strings, + is just fine.

 

 

 

13 Comments

Comments have been disabled for this content.