C# Tip: Use StringBuilder

5. November 2008 18:31

Okay, as an extension to the last post on String.Format, I'm doing a quick introduction to the System.Text.StringBuilder class.  Why, you ask.  Because when you append to a string, there is a lot of memory being allocated, transferred and dumped behind the scenes.  Say you have a string of "My string is" and you want to append " cool." what happens is a new string is allocated in memory, with enough space for the original string, and the appended value.  Then the original string is copied to the beginning, and the appended string is copied after.  This is very inneficient.  StringBuilder pre-allocates additional space, and handles the concatenation behind the scenes.

using System.Text;

namespace MyDemo
    class MyClass
        public string MyMethod()
            StringBuilder s = new StringBuilder();
            s.Append("My string is");
            s.Append(" cool");
            return s.ToString();

In the above example, you can see that it isn't at all difficult to use StringBuilder. You do need to remember to use the ToString() method to retrieve the internal value back as a string. There is one cool feature of StringBuilder that is related to the last post, that is the AppendFormat() method.

    "It is now {0}.",

With AppendFormat, you can add values into your StringBuilder class, as you would with a String.Format.  Now, if you want some similar functionality in JavaScript, you can always use an array, in place of a StringBuilder.  And use the push() method.  Once you have your array filled, you can use the join("") method, you need to use an empty string as the argument, as the default is a comma.

Comments are closed


Michael J. Ryan aka Tracker1

My name is Michael J. Ryan and I've been developing web based applications since the mid 90's.

I am an advanced Web UX developer with a near expert knowledge of JavaScript.