String concatenation vs String Builder. Performance

Solution 1:

The usual answer is that string concatenation is more efficient for between 4 to 8 strings. It depends on whose blog you read.

Don't write a test to decide on which method to use. If you are unsure of whether it will go over the magic limit, then just use StringBuilder.

Run this code to see the results for yourself:

const int sLen=30, Loops=5000;
DateTime sTime, eTime;
int i;
string sSource = new String('X', sLen);
string sDest = "";
// 
// Time string concatenation.
// 
sTime = DateTime.Now;
for(i=0;i<Loops;i++) sDest += sSource;
eTime = DateTime.Now;
Console.WriteLine("Concatenation took " + (eTime - sTime).TotalSeconds + " seconds.");
// 
// Time StringBuilder.
// 
sTime = DateTime.Now;
System.Text.StringBuilder sb = new System.Text.StringBuilder((int)(sLen * Loops * 1.1));
for(i=0;i<Loops;i++) sb.Append(sSource);
sDest = sb.ToString();
eTime = DateTime.Now;
Console.WriteLine("String Builder took " + (eTime - sTime).TotalSeconds + " seconds.");
// 
// Make the console window stay open
// so that you can see the results when running from the IDE.
// 
Console.WriteLine();
Console.Write("Press Enter to finish ... ");
Console.Read();

Ref. http://support.microsoft.com/kb/306822

Solution 2:

I support the idea of keeping things simple until you have a good reason to make them complex.

For something like 2-5 elements there is no point in using the StringBuilder (unless you repeat this concatenation continuously). The better readable syntax "+=" has more value.