String Concatenation

This topic has been covered many times by many programmers but I really enjoy these sort of programming tips. Playing with strings can be like playing with fire if you don’t take care – simple oversights can lead to large memory hogging and wasted processing time. In this post I want to discuss the best way to handle string concatenation. Strings are immutable and, in Garbage Collection environments, concatenating too many can significantly increase memory usage and processing time. The solution? Well, when using the .net framework, we have StringBuilder. If you are uncertain how many will concatenations [or you know there will be very many] then you should use StringBuilder – a benchmarked comparison is shown at http://support.microsoft.com/kb/306822.

So when you have code like this:

 

You should really consider changing it to:

 

 If you have an array of strings don’t bother looping through it, and you don’t even need StringBuilder, as you can simply [and efficiently] do this:

 

Keep these tips in mind when working with looped string concatenation and hopefully you can avoid another potential performance issue.  If you want to know more, Jon Skeet covered this with much more depth at http://www.yoda.arachsys.com/csharp/stringbuilder.html.

 

I should point out that there is little performance advantage to using StringBuilder (and string’s helper methods) when you are doing a simple string concatenation and you should always consider code readability too – Jeff Atwood covers this really well at http://www.codinghorror.com/blog/2009/01/the-sad-tragedy-of-micro-optimization-theater.html.