String ConcatenationAdd to My Brief

Matthew Boniface | 7/09/2011

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.

 

tags: Web Development

Interested in learning more?

Wiliam is a leading supplier of web solutions and can provide expert advice to assist your business or organisation online.

Make enquiry   Request quotation

Comments

Share this page

Print this page Email this page to a friend Bookmark and Share

No Brief added yet.

My Brief results-driven approach emphasises a commitment to our clients needs through strategic analysis and best-practice.

Add to My Brief

Click on this icon to save item into My Brief. Retrieve, email and print

Drag & Drop

Drag & drop any iten with this icon into My Brief. Retrieve, email and print

Search Blogs