20 April 2011

System.Text.StringBuilder is better than System.String for appending for append operations but...

For ages I've thought that by using a StringBuilder I could append to my strings with impunity.

But now I've just come across this post from Karl Seguin. In this post he says:
A StringBuilder is nothing more than a dynamic arrays for strings with some extra buffer space. When it fills up, it too must be copied to a new, larger, memory block.

So this is why System.Text.StringBuilder has several constructors that takes an Int32 with a specified capacity.

Referring to the MSDN library entry for System.Text.StringBuilder, under the Remarks section is this (emphasis mine):
This class represents a string-like object whose value is a mutable sequence of characters. The value is said to be mutable because it can be modified once it has been created by appending, removing, replacing, or inserting characters. For comparison, see the String class.

Most of the methods that modify an instance of this class return a reference to that same instance.


Also under Remarks is a sub-section entitled "Performance Considerations" that explains that whereas a concatenation operation on a System.String object always results in creating a new object, with a StringBuilder, a buffer is maintained and only once this is filled is a new, larger buffer created and the content copied into this.

So... I can't append to StringBuilders with impunity. A better practice that will yield performance benefits is to allocate sufficient space in the constructor. I can't do this with System.String (there's no constructor that allows me to specify a length). System.String objects are immutable.

No comments:

Post a Comment