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.

s.AppendFormat(
    "It is now {0}.",
    DateTime.Now
);

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

11/5/2008 6:59:44 PM #

trackback

Trackback from DotNetKicks.com

C# Tip: Use StringBuilder

DotNetKicks.com |

2/14/2009 9:30:46 AM #

John Wightman

string.Format is useful if you want to apply some formatting to a non string value, such as a DateTime or double type, but string concatenation wins hands down with performance if all you want to do is append some string together.

John Wightman United Kingdom |

2/17/2009 4:09:48 PM #

tracker1

John, sometimes readability is more important than raw performance.  Also, StringBuilder will outperform concatenation += on multiple lines.  For a single line, or two, string concatenation is faster than the overhead of stringbuilder.  However, memory allocation/copy/insert repeated is slower after a few runs than the pre-allocation of memory space that StringBuilder gives you.

tracker1 United States |

Comments are closed

Tracker1

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.