I always know that StringBuilder is recommended when adding strings dynamically,
but how huge the difference is?
Following is the sample code.
DateTime start = DateTime.Now; string str = "1234567890"; string longer = ""; for (int i = 0; i < 100000; i++) { longer += str; } DateTime end = DateTime.Now; TimeSpan ts = new TimeSpan(end.Ticks - start.Ticks); Console.WriteLine(ts); DateTime start2 = DateTime.Now; StringBuilder sb = new StringBuilder(); for (int i = 0; i < 100000; i++) { sb.Append(str); } DateTime end2 = DateTime.Now; TimeSpan ts2 = new TimeSpan(end2.Ticks - start2.Ticks); Console.WriteLine(ts2); Console.ReadKey();And this is the result.
沒有留言:
張貼留言