string与stringBuilder的性能区别(转)
自己动手测试了,性能差距还比较大:
Console.WriteLine("Class String:"); string strClass = string.Empty; DateTime BeginTime = System.DateTime.Now; Console.WriteLine(BeginTime.ToString()); for (int i = 0; i <= 99999; i++) { strClass += i.ToString(); } DateTime EndTime = System.DateTime.Now; Console.WriteLine(EndTime.ToString()); TimeSpan ts = EndTime.Subtract(BeginTime); Console.WriteLine("class string cost time is:" + ts.TotalMilliseconds.ToString() + "ms"); Console.WriteLine(); Console.WriteLine("Class StringBulid:"); StringBuilder sb = new StringBuilder(); Console.WriteLine(System.DateTime.Now.ToString()); BeginTime = System.DateTime.Now; for (int i = 0; i <= 99999; i++) { sb.Append(i.ToString()); } Console.WriteLine(System.DateTime.Now.ToString()); EndTime = System.DateTime.Now; ts = EndTime.Subtract(BeginTime); Console.WriteLine("class stringbuild cost time is:" + ts.TotalMilliseconds.ToString() + "ms");
结果:
Class String:
2008-12-24 13:33:29
2008-12-24 13:34:29
class string cost time is:60453.125ms
Class StringBulid:
2008-12-24 13:34:29
2008-12-24 13:34:29
class stringbuild cost time is:31.25ms
请按任意键继续. . .