Why the speed rank is: AddStringInMutipleStatement > AddStringInOneStatement > AddStringInMutipleStatementEx ?
Is it related the temp string object created on runtime? What the detail is?
namespace Test
{
class Program
{
static string AddStringInOneStatement(int a, string b, int c, string d)
{
string str;
str = "a = " + a.ToString() + "b = " + b + "c = " + c.ToString() + "d = " + d;
return str;
}
static string AddStringInMutipleStatement(int a, string b, int c, string d)
{
string str = "";
str += "a = " + a.ToString();
str += "b = " + b;
str += "c = " + c.ToString();
str += "d = " + d;
return str;
}
static string AddStringInMutipleStatementEx(int a, string b, int c, string d)
{
string str = "";
str += "a = ";
str += a.ToString();
str += "b = ";
str += b;
str += "c = ";
str += c.ToString();
str += "d = ";
str += d;
return str;
}
static void Main(string[] args)
{
uint times = 10000000;
Stopwatch timer = new Stopwatch();
timer.Start();
for (int i = 0; i < times; i++)
{
AddStringInOneStatement(1, "2", 3, "4");
}
timer.Stop();
Console.WriteLine("First: " + timer.ElapsedMilliseconds); // 4341 ms
timer.Reset();
timer.Start();
for (int i = 0; i < times; i++)
{
AddStringInMutipleStatement(1, "2", 3, "4");
}
timer.Stop();
Console.WriteLine("Second: " + timer.ElapsedMilliseconds); // 3427 ms
timer.Reset();
timer.Start();
for (int i = 0; i < times; i++)
{
AddStringInMutipleStatementEx(1, "2", 3, "4");
}
timer.Stop();
Console.WriteLine("Second: " + timer.ElapsedMilliseconds); // 5701 ms
}
}
}