Appending string in C#: String += vs string.Format vs StringBuilder

Appending strings performance test

String += creates new instance of object and saves it in memory, as a result you have 2 string objects in a memory. For this kind of targets .NET have class named StringBuilder which will work 2500 times faster than string += or trick with string.Format (which is a very bad idea). StringBuilder holds all data in one memory instance and changes it, not creates a new instance each time as it do += for string.

So better practice for appending strings is to use StringBuilder.

C# code:

int iterations = 100000;

 

string testString = string.Empty;

 

// string += test (using string.Concat will return the same result)

Stopwatch sw = new Stopwatch();

sw.Start();

 

for (int i = 0; i < iterations; ++i)

{

    testString += i.ToString();

}

 

sw.Stop();

 

Console.WriteLine(sw.ElapsedMilliseconds);

 

sw.Reset();

 

// string.Format test

testString = string.Empty;

sw.Start();

 

for (int i = 0; i < iterations; ++i)

{

    testString = string.Format("{0}{1}", testString, i.ToString());

}

 

sw.Stop();

 

Console.WriteLine(sw.ElapsedMilliseconds);

 

sw.Reset();

 

// StringBuilder test

StringBuilder sb = new StringBuilder();

sw.Start();

 

for (int i = 0; i < iterations; ++i)

{

    sb.Append(i.ToString());

}

 

testString = sb.ToString();

 

sw.Stop();

 

Console.WriteLine(sw.ElapsedMilliseconds);

 

Console.ReadKey();

Results:

  1. string += appending : 176 654 ms
  2. string.Format appending : 456 265 ms
  3. StringBuilder.Append() :  68 ms

5 Comments

Comments have been disabled for this content.