C# String和String Builder效率比较

Posted 一身千寻瀑

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了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();
        
    


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

运行结果


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

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

2016.3.14

以上是关于C# String和String Builder效率比较的主要内容,如果未能解决你的问题,请参考以下文章

String Buffer和String Builder的区别(转)

Java基础16-String类(Buffer和Builder)

C#字符串比较方法Compare()

String String Buffer String Builder

go语言string之Buffer与Builder

JAVA高级特性--String/StringBuffer/Builder