Sunday, April 4, 2010

Using the StringBuilder class

In .NET I often see people use the plus ‘+’ operator in C# or the ampersand ‘&’ operator in VB.NET to concatenate strings. Whenever these operators are use for concatenation the Framework copies all the strings included in the operation into memory and then reads back those value as a new string. This, even if it doesn’t seem to be, is a costly operation. This is where the StringBuilder comes in. This class, as MSDN describes it is “ 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.” And the important thing to know is that it is faster than using concatenation operators as you can see in the following example.



using System;
using System.Collections.Generic;
using System.Text;

namespace Test
{
    class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine("Concatenation using string class and operators");
            string s = string.Empty;
            Console.WriteLine("Operation start time: " + DateTime.Now.ToLongTimeString());
            for (int i = 0; i < 100000; i++)
            {
                s += i.ToString();
            }
            Console.WriteLine("Operation stop time: " + DateTime.Now.ToLongTimeString());

            Console.WriteLine();

            Console.WriteLine("Concatenation using StringBuilder");
            StringBuilder sb = new StringBuilder(string.Empty);
            Console.WriteLine("Operation start time: " + DateTime.Now.ToLongTimeString());
            for (int i = 0; i < 100000; i++)
            {
                sb.Append(i);
            }
            Console.WriteLine("Operation stop time: " + DateTime.Now.ToLongTimeString());

            Console.WriteLine();
            Console.WriteLine("Press any key to close this window.");
            Console.ReadLine();
        }
    }
}







Sure if you only concatenate a couple of strings you won’t see the difference but still, I think that using the StringBuilder class whenever you need to manipulate a string is a good habit to take.

No comments:

Post a Comment