您的位置:首页 > 产品设计 > UI/UE

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

2013-01-21 10:48 501 查看
最新文章:Virson's Blog

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

CSharp代码:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Diagnostics;

namespace TestCharactor
{
class TestChar
{
private static int times = 50000;    //循环次数
private static Stopwatch sw = new Stopwatch();

static void Main(string[] args)
{
string tmpS = "adcdefg";
StringBuilder tmpSb = new StringBuilder("abcdefg");
sw.Start();
Test(tmpS);
sw.Stop();
Console.WriteLine("使用+操作符连接字符串共花费时间:{0}毫秒", sw.ElapsedMilliseconds);
sw.Restart();
Test(tmpSb);
sw.Stop();
Console.WriteLine("使用StringBuilder类连接字符串共花费时间:{0}毫秒", sw.ElapsedMilliseconds);
Console.ReadKey();
}

public TestChar()
{

}

public static void Test(String s)
{
//sw.Start();
for (int i = 0; i < times; ++i )
{
s += "Virson Ma";
}
//sw.Stop();
//Console.WriteLine("使用+操作符连接字符串共花费时间:{0}毫秒", sw.ElapsedMilliseconds);
}

public static void Test(StringBuilder sb)
{
//sw.Restart();
for (int i = 0; i < times; ++i )
{
sb.Append("Virson Ma");
}
//sw.Stop();
//Console.WriteLine("使用StringBuilder类连接字符串共花费时间:{0}毫秒", sw.ElapsedMilliseconds);
}
}
}


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

Result:

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐