Tuesday, June 23, 2009

System.String Vs System.Text.StringBuilder

The System.String object is immutable, once set, the content of a String object cannot be modified. Trying to change its value succeeds, but this actually destroys the old String object and creates a new one, which requires a new allocation of space for that new object. In situations where you need to perform repeated modifications to a string, the overhead associated with creating a new String object can be costly.

The System.Text.StringBuilder class can be used when you want to modify a string without creating a new object. It will not create a new string object but instead append to the existing string. For example, using the StringBuilder class can boost performance when concatenating many strings together in a loop.

The StringBuilder's initial capacity is set to 16 by default. The capacity then increases by an order of 2 whenever the current capacity is passed.

The size of a StringBuilder object's storage can be obtained from the class' Capacity property. The length of the string in a StringBuilder object can be obtained from its Length property. The capacity can be increased or decreased with the Capacity property or EnsureCapacity method, but it cannot be less than the value of the Length property.