Tuesday, January 31, 2006

string.Concat vs the + operator in C#

I was in an interview last week and I was asked what were the three ways of concatenating a string in .NET and which I would choose to use. I could only think of two, using the + operator and using a StringBuilder but guessed there must be string.Concat as well, which I've never used. I said I'd use a StringBuilder in code that got called a lot or a loop and I'd use the + operator any other time. The interviewer told me the + operator had some serious performance problems and I thought "does it???" So I thought I better investigate. I wrote a simple app to concatenate strings and checked in Reflector to see how using the + operator and string.Concat differed. The first thing to note is that the string class doesn't actually overload the + operator and looking at the IL for my app, the + operator version of the code, by some compiler magic I presume, actually got converted to calls to string.Concat. The IL in both cases was exactly the same. So I'll stick with "a" + "b"...

4 comments:

Anonymous said...

I believe the issue is with multiple concatenations. For example something like "a" + "b" + "c" + "d" creates a new object "cd" in memory, then a new object "bcd", and then finally "abcd". You can see where this could become a problem if large numbers of strings were concatenated this way. Whereas String.Concat does them all at once without the intermediate copies.

Doogal said...

I've added a new post going into more detail on the subject

Anonymous said...

"a" + "b" + "c"

According to microsoft the above code would be changed to a single string, "abc", at compile time. Meaning no performace issue during run time. There is a time and place for everything.

II ARROWS said...

Well... I think the example has been made with "a"+"b"+"c", but in a real environment you would rather use a+b+c.
Objects that the compiler cannot join. ;)