Strings are immutable. In other words, a string can not be changed once assigned. When you append a string to an existing string, the .NET framework actually creates a new string containing the original string and the appended string. This is a resource-hungry and time-consuming process.

The alternative to appending strings, is the StringBuilder class which is somewhat hidden in the System.Text namespace. The class is faster because it allocates an initial space when an instance of it is created. By default, a StringBuilder object created using the StringBuilder class default constructor reserves a space of 16 characters in memory. This default can be overloaded.

Generally, the recommended cutoff number is five. If you have more than five separate string concatenations, StringBuilder is generally more efficient than appending the strings.

2 Comments to “Improve String Management with StringBuilder”

  1. [...] StringBuilder should be used to better performance.  Blah… Blah… Blah…  You’ve heard it all before, but what you might not know is how StringBuilder dynamically allocates its capacity.  The [...]

  2. Thank you very much for this article! This information was very usefull for me=)

Leave a Reply

You can wrap your code with [ruby][/ruby] or [python][/python] blocks for syntax highlighting and you can use these traditional tags: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>