Reputation: 67260
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
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):
Upvotes: 15