static void Main(string[] args)
{
for (int j = 0; j < 5; j++)
{
//第一种方法
Stopwatch watch = new Stopwatch();
watch.Start();
string output;
string strB = default(string);
for (int i = 0; i < 100000000; i++)
{
strB = "Good morning, Good morningGood morningGood morningGood morningGood morningGood morningGood morningGood morningGood morningGood morningGood morningGood morningGood morningGood morningGood morningGood morningGood morningGood morningGood morningGood morningGood morningGood morningGood morningGood morningGood morningGood morningGood morningGood morningGood morningGood morningGood morningGood morningGood morningGood morningGood morningGood morningGood morningGood morningGood morningGood morningGood morningGood morningGood morningGood morningGood morningGood morningGood morningGood morningGood morningGood morningGood morningGood morningGood morning";
strB += "world";
}
output = strB;
watch.Stop();
TimeSpan time = watch.Elapsed;
Console.WriteLine("time new:" + time);
//第二种方法:先开辟一定的空间,然后向里面赋值
Stopwatch watchA = new Stopwatch();
watchA.Start();
string strValue = "Good morning, Good morningGood morningGood morningGood morningGood morningGood morningGood morningGood morningGood morningGood morningGood morningGood morningGood morningGood morningGood morningGood morningGood morningGood morningGood morningGood morningGood morningGood morningGood morningGood morningGood morningGood morningGood morningGood morningGood morningGood morningGood morningGood morningGood morningGood morningGood morningGood morningGood morningGood morningGood morningGood morningGood morningGood morningGood morningGood morningGood morningGood morningGood morningGood morningGood morningGood morningGood morningGood morningGood morning";
string strWorld = "world";
char[] array = new char[1024];
for (int i = 0; i < 100000000; i++)
{
strValue.CopyTo(0, array, 0, strValue.Length);
strWorld.CopyTo(0, array, strValue.Length, strWorld.Length);
}
output = new string(array);
watchA.Stop();
TimeSpan timeA = watchA.Elapsed;
Console.WriteLine("time array:" + timeA);
//第三种方法:StringBuilder方式
Stopwatch watchB = new Stopwatch();
watchB.Start();
StringBuilder strValue1 = new StringBuilder(1024);
for (int i = 0; i < 100000000; i++)
{
strValue1.Clear();
strValue1.Append(strValue);
strValue1.Append(strWorld);
}
output = strValue1.ToString();
watchB.Stop();
TimeSpan timeB = watchB.Elapsed;
Console.WriteLine("time stringBuilder:" + timeB);
Console.WriteLine();
}
}
结果如附图:
![]()
![]()
从上面的结果可以看出,stringBuilder性能更优越