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
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):
UPDATE:
Using following test:
I meassured these results on my computer (Intel Core2 Q9400, Windows Server 2008 x64, .NET Framework 4.0, Release mode):