Guy
Guy

Reputation: 67260

StringBuilder Append vs AppendFormat efficiency in C#

Which is more efficient in C#, 1 or 2?

StringBuilder sb = new StringBuilder();
sb.Append("my string " + myVar + " my string");     // 1
sb.AppendFormat("my string {0} my string", myVar);  // 2

I'm guessing that the question could also be rephrased:

string y = "my string " + myVar + " my string";              // 1
string x = String.Format("my string {0} my string", myVar);  // 2

Upvotes: 0

Views: 7297

Answers (1)

Ňuf
Ňuf

Reputation: 6207

Version of .NET Framework is important here, because implementation of StringBuilder.Append and StringBuilder.AppendFormat can differ significantly between individual versions. Under .NET Framework 4, (1) is faster than (2), but it is still inefficient because of overhead caused by concatenating (and thus copying) of (sub)strings. This is even 2x faster than (1):

StringBuilder sb = new StringBuilder();
sb.Append("my string");
sb.Append(myVar);
sb.Append(" my string");


UPDATE:
Using following test:

static void Main(string[] args)
{
    string myVar = "abcdef";
    Stopwatch stopwatch = Stopwatch.StartNew();

    for (int j = 0; j < 10000; j++)
    {
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < 10000; i++)
        {
            //UNCOMMENT ONE OF THESE TESTS
            //Test1
            sb.Append("my string " + myVar + " my string");

            //Test2
            //sb.AppendFormat("my string {0} my string", myVar);

            //Test3
            //sb.Append("my string ");
            //sb.Append(myVar);
            //sb.Append(" my string");
        }
    }
    stopwatch.Stop();
    Console.WriteLine(stopwatch.ElapsedMilliseconds + " ms");
}

I meassured these results on my computer (Intel Core2 Q9400, Windows Server 2008 x64, .NET Framework 4.0, Release mode):

  • Test1: 10401 ms
  • Test2: 20262 ms
  • Test3: 5771 ms

Upvotes: 15

Related Questions