volatile constants

Saturday, May 27, 2006

The StringBuilder Code

Common understanding is that, when we need to concatenate a few strings together to make a happy string, we will typically use StringBuilder, having heard so many preaching about the performance gain as opposed to using the "+" operator.

Well that is true in almost all situations. However, there are a few misconceptions as well. Typically, a StringBuilder object comes in handy when we are building the strings in a loop, and the number of string variables exceed 5 or more. When using StringBuilder to concatenate less than that amount of string, it becomes a hinder to performance rather than helping it as we know there are overheads involved in initializing the StringBuilder object.

Now, for small amount of string, we should use String.Concat(), it can't get any faster than that. Which means, the following code in Snippet B is not as good as Snippet A.

Code Snippet A

static void Main(string[] args)
{
string output1 = "Hello";
string output2 = "World";

Console.WriteLine(output1 + output2);
}

Code Snippet B

static void Main(string[] args)
{

string output1 = "Hello";
string output2 = "World";

Console.WriteLine(String.Concat(output1, output2));
}

The answer is NO. They are both the SAME!
Why? Simply inspect the IL code using ILDASM, we see

.method private hidebysig static void Main(string[] args) cil managed
{

.entrypoint
.custom instance void [mscorlib]System.STAThreadAttribute::.ctor() = ( 01 00 00 00 )
// Code size 25 (0x19)
.maxstack 2
.locals init (string V_0, string V_1)
IL_0000: ldstr "Hello"
IL_0005: stloc.0
IL_0006: ldstr "World"
IL_000b: stloc.1
IL_000c: ldloc.0
IL_000d: ldloc.1
IL_000e: call string [mscorlib]System.String::Concat(string,string)
IL_0013: call void [mscorlib]System.Console::WriteLine(string)
IL_0018: ret
} // end of method StringPerformance::Main

Both codes compiled to the same IL. C#'s compiler itself actually optimizes the string concatenation to use string.concat.

Final word: Don't abuse StringBuilder. Use when concatenating a dynamically growing number of strings.


17 Comments:

Post a Comment

<< Home