我用c#写了两个stopwatch测试一下stringbuilder和string循环写入的速度差异。
代码是:
int n = 500;
Stopwatch time = new Stopwatch();
time.Start();
StringBuilder xx = new StringBuilder();
while (n > 0)
{
n--;
xx.Append(n);
Console.WriteLine(xx);
}
xx.Clear();
time.Stop();
Console.WriteLine("stringbuilder:" + time.Elapsed);
time.Start();
string a = "";
while (n > 0)
{
n--;
a = a + Convert.ToString(n);
Console.WriteLine(a);
}
time.Stop();
Console.WriteLine("string:" + time.Elapsed);
Console.ReadKey();
但是在控制台的输出结果一看,是先把两个循环的输出完了再把结果直接打印出来。
你的程序有2个问题
第一,
n = 500; //加上
while (n > 0)
{
n--;
a = a + Convert.ToString(n);
Console.WriteLine(a);
}
没有这一行,你调试下,n是0,所以第二个循环根本没有跑,所以输出了stringbuilder后直接输出了string
另一个问题是,你在循环里输出字符串,这个会浪费很多时间,所以你要比较string加法和stringbuilder,最好不要在循环里每次输出一个数字。