C# Info: StringBuilder vs String Concatenation example,

Hello,

So I have a project at home I work on (normally in the morning before work). Long story short, it involves a class that has methods for spitting out things mainly for shader development.

So in order to show why/how StringBuilder is faster for concatenation than just strings (stringBuilder.Append(“example”) vs string += “example”, etc.), I wrote this little C# test yesterday.

The thing is, since strings are immutable, concatenation just creates a new string, so often people do not realize how many new strings are created.

Long story short, 20000 appends with stringbuilder takes 4 milliseconds vs 1016 milliseconds for concatenations (depending on your machine),

If you find some error in my logic, let me know :):

[highlight=C#]
using System;
using System.Collections.Generic;
using System.Text;
using System.Diagnostics;

namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
int numberOfLoops = 20000;

        Stopwatch stringBuilderTimer = Stopwatch.StartNew();
        stringBuilderAppend(numberOfLoops);
        stringBuilderTimer.Stop();

        Console.WriteLine("{0} appends with the string builder took {1} milliseconds.

", numberOfLoops, stringBuilderTimer.ElapsedMilliseconds);

        Stopwatch stringConcatTimer = Stopwatch.StartNew();
        stringConcat(numberOfLoops);
        stringConcatTimer.Stop();


        Console.WriteLine("{0} concatenations with the string builder took {1} milliseconds.

", numberOfLoops, stringConcatTimer.ElapsedMilliseconds);
Console.ReadLine();
}

    private static void stringBuilderAppend(int numberIterations)
    {
        StringBuilder aString = new StringBuilder();
        for (int i = 0; i < numberIterations; i++)
        {
            aString.Append(i.ToString());
        }
    }

    private static void stringConcat(int numberIterations)
    {
        string aString = null;
        for (int i = 0; i < numberIterations; i++)
        {
            aString += (i.ToString());
        }
    }
}

}



Of course, if it's just few concatenations, it may not be worth the effort, but keep it in mind the larger you go. :):

(Side Note: This may be "old-hat" for some)

http://blogs.msdn.com/b/ricom/archive/2003/12/02/40778.aspx

Thanks for the link.