知道“StringBuilder比string性能强”好多年了,近日无聊病发作,就把这两个家伙给动了手术:
using System;
using System.Text;
namespace ConsoleApplication1
{
classProgram
{
staticvoid Main(string[] args)
{
int start = Environment.TickCount; //计时打点
fun1();
int middle = Environment.TickCount; //计时打点
fun2();
int end = Environment.TickCount; //计时打点
Console.WriteLine("string 运行时间 {0} 秒", 0.001 * (middle - start));
Console.WriteLine("StringBuilder 运行时间 {0} 秒", 0.001 * (end - middle));
Console.ReadKey();
}
//fun1和fun2是两个结构功能相同的无聊耗时方法
privatestaticvoid fun1()
{
for (int i = 0; i < 1000; i++)
{
string s = "";
for (int j = 0; j < 200; j++)
{
s += "Outer index = ";
s += i;
s += " Inner index = ";
s += j;
s += " ";
}
}
}
privatestaticvoid fun2()
{
for (int i = 0; i < 1000; i++)
{
StringBuilder s = newStringBuilder();
for (int j = 0; j < 200; j++)
{
s.Append("Outer index = ");
s.Append(i);
s.Append("Inner index = ");
s.Append(j);
s.Append(" ");
}
}
}
}
}
可见区别之大。
用vs自带的性能分析工具分析如下(过程比较慢):
查看函数详细信息:
可见fun1明显比fun2的非独占分配数大,如果想进一步了解细节,可点击相应区域,结果如下
接下去,你懂得。。。