C#中常用直接相加的方式进行字符串拼接,但是还有一种StringBuilder的拼接方式,现在对比他们之间的性能影响。
C#代码如下
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Diagnostics;
namespace NiuKe_TEST
{
class Program
{
static void Main(string[] args)
{
Stopwatch sw = new Stopwatch();
sw.Start();
UserContrast.UserFirstWay("HAHA", 60000);
sw.Stop();
Console.WriteLine("使用字符串拼接60000次耗时:" + sw.ElapsedMilliseconds);
//sw.Start();
//UserContrast.UserSecWay("HAHA", 60000);
//sw.Stop();
//Console.WriteLine("使用StringBuilder拼接60000次耗时:" + sw.ElapsedMilliseconds);
}
}
public static class UserContrast
{
public static string UserFirstWay(string strValue, int num)
{
string result = "";
for(int i=0;i<num;i++)
{
result += strValue + i;
}
return result;
}
public static string UserSecWay(string strValue, int num)
{
StringBuilder sb = new StringBuilder();
for (int i = 0; i < num; i++)
{
sb.Append(strValue+i);
}
return sb.ToString();
}
}
}
通过上述代码我的机子跑出来分别是使用传统的相加和StringBuilder进行字符串的拼接耗时分别是10615ms和13ms,由此可看出来使用StringBuilder的进行字符串的拼接速度快了不只是一点点。