【C#】 String和String Builder效率比较

本文是关于String和String Builder的工作效率的测试。

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

namespace CompareStrAndStrBuilder
{
    class Program
    {
        static void Main(string[] args)
        {
            const int sLen = 30, Loops = 5000;
            DateTime sTime, eTime;
            int i;
            string sSource = new string('X', sLen);
            string sDest = "";

            //---Time String Concaternation---
            sTime = DateTime.Now;
            for (i = 0; i < Loops; ++i)
                sDest += sSource;
            eTime = DateTime.Now;
            Console.WriteLine("Concatenation took " + (eTime - sTime).TotalSeconds + " seconds.");

            //---Time StringBuilder---
            sTime = DateTime.Now;
            StringBuilder sb = new StringBuilder((int)(sLen * Loops * 1.1));
            for (i = 0; i < Loops; ++i)
                sb.Append(sSource);
            sDest = sb.ToString();
            eTime = DateTime.Now;
            Console.WriteLine("String Builder took " + (eTime - sTime).TotalSeconds + " seconds.");

            Console.ReadKey();
        }
    }
}

--------------------------------------

运行结果

【C#】 String和String Builder效率比较_第1张图片

由此可见String Builder的效率很快,持续之短让我这渣电脑看不出来String Builder的运行时间。比普通String的操作效率高出数个数量级。

----------------------------------

2016.3.14

你可能感兴趣的:(C#,c#,String,String,Builder,效率)