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:

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值