我用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();
但是在控制台的输出结果一看,是先把两个循环的输出完了再把结果直接打印出来。