所以我在想什么更有效率,通过直接将它们作为字符串添加到彼此或字符串来形成数字。格式化它们。
所以我做了一个小代码:
private static void measuringStuff()
{
Stopwatch stw = new Stopwatch();
Random random = new Random();
string a;
stw.Start();
for (int i = 0; i < 10000000; i++)
{
a = random.Next(10) + "" + random.Next(10);
}
stw.Stop();
Console.WriteLine("#+\"\"+#: " + stw.ElapsedMilliseconds);
stw.Reset();
stw.Start();
for (int i = 0; i < 10000000; i++)
{
a = string.Format("{0}{1}", random.Next(10), random.Next(10));
}
stw.Stop();
Console.WriteLine("string.Format: " + stw.ElapsedMilliseconds);
}
事实证明:
# + "" + #: 1928
string.Format: 2667
为什么?