«

»

Oct 16

.NET System.String vs System.Text.StringBuilder




Strings in .NET are Immutable and can be very inefficient

Once you assign an initial value to a System.String object the data cannot be changed.  This may seem incorrect because it looks like the value can be changed in code, but in reality any change made to a String results in a brand new String with the changed value.   Understanding this is important so that we are aware of the inefficiencies of using the String type.  If we had an application doing a lot of string processing there would be a performance penalty with using String types.

There is a great example of how String.Append is exponentially inefficient as string size increases on this web blog.

Thankfully .NET has the StringBuilder type in the System.Text namespace.  The StringBuilder contains methods that help you with basic string manipulation and when you modify a string in code you are modifying the internal representation of that string in memory rather than making copies of it every time you make a change.

String manipulation example

String myString = "This string is immutable!";
myString = "Wait a second, I just changed the immutable string, didn't I?";

If you were to look at the CIL code generated in the above example, you’ll see two different strings being stored in memory.

StringBuilder Manipulation Example

using System.Text;
StringBuilder sb = new StringBuilder("This string can be changed");
sb.Append(".\n");
sb.Appendsb.AppendLine("Like this.");
sb.Replace(".","!");
myString = sb.ToString();

The above example modifies the string in memory and then assigns the resultant value to a string.