【发布时间】:2014-04-09 07:43:06
【问题描述】:
为什么速度排名是:AddStringInMutipleStatement > AddStringInOneStatement > AddStringInMutipleStatementEx?
它是否与运行时创建的临时字符串对象有关?细节是什么?
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
}
}
}
【问题讨论】:
-
我建议在这里使用 String.Format()。
-
您如何对速度进行基准测试?
-
+1,这是一个合理的问题。我可以重现您的观察结果(发布版本):3078ms、2530ms、3297ms。
-
你也应该在这里使用 StringBuilder 进行这样的连接,并有助于内存使用,也许还有性能。
标签: c# string concatenation