Thursday, September 16, 2010

C# StringBuilder vs String Concatenation

Use StringBuilder for string concatenation. Concatenation of string using StringBuilder has better performance over string.
Below code measures the time taken to concatenate a string for 5000 iteration using “string” and “StringBuilder”.
using System;
using System.Collections.Generic;
using System.Text;
using System.Diagnostics;
namespace StringVsStringBuilder
{
    class Program
    {
        static void Main(string[] args)
        {
            Stopwatch objStopwatch = new Stopwatch();
            string strValue=string.Empty;
            StringBuilder objSBValue = new StringBuilder();
            int iCount = 5000;
            objStopwatch.Reset();
            objStopwatch.Start();
            for (int i = 0; i < iCount; i++)
            {
                strValue = strValue+"simpleValue"+i.ToString();
            }
            objStopwatch.Stop();
            Console.WriteLine("concatenation using String.");
            Console.WriteLine(
                "TimeElapsed (Stopwatch float):{0}ms",
                objStopwatch.Elapsed.TotalMilliseconds
                );
            Console.WriteLine(
                "TimeElapsed (Stopwatch rounded):{0}ms",
                objStopwatch.ElapsedMilliseconds
                );
            //Console.WriteLine(strValue);
            objStopwatch.Reset();
            objStopwatch.Start();
            for (int i = 0; i < iCount; i++)
            {
                objSBValue.Append("simpleValue" + i.ToString());
            }
            objStopwatch.Stop();
            Console.WriteLine(
                "concatenation using StringBuilder."
                );
            Console.WriteLine(
                "TimeElapsed (Stopwatch float):{0}ms",
                objStopwatch.Elapsed.TotalMilliseconds
                );
            Console.WriteLine(
                "TimeElapsed (Stopwatch rounded):{0}ms",
                objStopwatch.ElapsedMilliseconds
                );
            //Console.WriteLine(objSBValue);
            Console.ReadLine();
        }
    }
}
Output:
concatenation using String.
TimeElapsed (Stopwatch float):316.6526ms
TimeElapsed (Stopwatch rounded):316ms
concatenation using StringBuilder.
TimeElapsed (Stopwatch float):2.4933ms
TimeElapsed (Stopwatch rounded):2ms

Why? Any object stored in heap is immutable with respect to size allocation, and any change to the underlying size will require reallocation. If the string is modified (concatenating another string onto it, changing its value), then a new string is created and this can have negative performance implications. The StringBuilder gets around the reallocation problem by using internal buffers. But once the buffer fills up, the reallocation occurs. It is recommended to specify the initial capacity to minimize the reallocation problem.

Rule: Use StringBuilder instead of string for string concatenation operation.

No comments: