Here is 2 methods which result the same:
public class MessageManager
{
public void SendMessage(string name, int count)
{
string message = "Hi " + name + ". I know you don't like cake, so I bought you " + count + " lollipops. Same thing, right?"; // No boxing. "count" was converted to string somehow.
//Console.WriteLine(message);
}
public void SendMessage2(string name, int count)
{
string message = String.Format("Hi {0}. I know you don't like cake, so I bought you {1} lollipops. Same thing, right?", name, count); // Boxing "name" and "count" + executing unnecessary code.
//Console.WriteLine(message);
}
}
So I guess the second method will be slower then first because of boxing and executing some additional code which inside String.Format() method.
I have tested them with following method:
public static class PerformanceTester
{
public static TimeSpan TestAction(Action<string, int> action)
{
Stopwatch timer = new Stopwatch();
timer.Start();
for (ushort i = 0; i < ushort.MaxValue; i++)
action("Alex", 1000);
timer.Stop();
return timer.Elapsed;
}
}
And here is the usage of it:
static void Main(string[] args)
{
MessageManager mm = new MessageManager();
TimeSpan ts_m1 = PerformanceTester.TestAction(new Action<string, int>(mm.SendMessage));
TimeSpan ts_m2 = PerformanceTester.TestAction(new Action<string, int>(mm.SendMessage2));
Console.WriteLine("First message took time: " + ts_m1.ToString());
Console.WriteLine("Second message took time: " + ts_m2.ToString());
Console.ReadKey();
}
Output with my Intel® Core™2 Duo Processor E8200 (DEBUG):
Output with my Intel® Core™2 Duo Processor E8200 (RELEASE):
I saw String.Format used almost everywhere (guides, blogs, tutorials etc.) but it is actually slower than simple string concatenation. I know when I talk about C# I must not care about performance, but the results in this example is too awesome. The question is: "Is there any best practice where String.Format is actually better than concatenation of strings."