String与StringBuilder性能比较
在大量数据的情况下,两者的差距就明显了!
String str1 = String.Empty;
StringBuilder sb1 = new StringBuilder();
Stopwatch watch1 = new Stopwatch();
watch1.Start();
for (var i = 0; i < 100000; i++)
{
str1 += "add" + i.ToString();
}
watch1.Stop();
Stopwatch watch2 = new Stopwatch();
watch2.Start();
for (var i = 0; i < 100000; i++)
{
sb1.Append("add" + i.ToString());
}
watch2.Stop();
Console.WriteLine("Reflection: " + watch1.Elapsed);
Console.WriteLine("Reflection: " + watch2.Elapsed);
Console.ReadLine();
结果为
Reflection: 00:02:09.5819695
Reflection: 00:00:00.0659941
在10000次的性能上,都在10倍左右,但都小于0。1秒