String、StringBuilder类连接字符串操作的时间差异

最新文章:Virson's Blog

刚刚看到园子里面写了一篇关于Java的《StringBuilder、StringBuffer、String类之间的关系》的文章,自己也想试试看C#的String和StringBuilder类之间的差异,于是有了这篇文章:

CSharp代码:

 1 using System;
 2 using System.Collections.Generic;
 3 using System.Linq;
 4 using System.Text;
 5 using System.Threading.Tasks;
 6 using System.Diagnostics;
 7 
 8 namespace TestCharactor
 9 {
10     class TestChar
11     {
12         private static int times = 50000;    //循环次数
13         private static Stopwatch sw = new Stopwatch();
14 
15         static void Main(string[] args)
16         {
17             string tmpS = "adcdefg";
18             StringBuilder tmpSb = new StringBuilder("abcdefg");
19             sw.Start();
20             Test(tmpS);
21             sw.Stop();
22             Console.WriteLine("使用+操作符连接字符串共花费时间:{0}毫秒", sw.ElapsedMilliseconds);
23             sw.Restart();
24             Test(tmpSb);
25             sw.Stop();
26             Console.WriteLine("使用StringBuilder类连接字符串共花费时间:{0}毫秒", sw.ElapsedMilliseconds);
27             Console.ReadKey();
28         }
29 
30         public TestChar()
31         {
32 
33         }
34 
35         public static void Test(String s)
36         {
37             //sw.Start();
38             for (int i = 0; i < times; ++i )
39             {
40                 s += "Virson Ma";
41             }
42             //sw.Stop();
43             //Console.WriteLine("使用+操作符连接字符串共花费时间:{0}毫秒", sw.ElapsedMilliseconds);
44         }
45 
46         public static void Test(StringBuilder sb)
47         {
48             //sw.Restart();
49             for (int i = 0; i < times; ++i )
50             {
51                 sb.Append("Virson Ma");
52             }
53             //sw.Stop();
54             //Console.WriteLine("使用StringBuilder类连接字符串共花费时间:{0}毫秒", sw.ElapsedMilliseconds);
55         }
56     }
57 }

测试结果可以看出使用StringBuilder的Append方法比String的“+”操作要节省很多时间!

Result:

原文地址:https://www.cnblogs.com/mawanglin2008/p/2869363.html