string类与StringBuilder类性能比较(采用Stopwatch类)

修改了下上次写过的一篇string类与StringBuilder类性能比较 http://www.ajaxcn.net/archives/499,这次使用Stopwatch类,

使计算的时间更为准确,从结果来看,字符100个string的时候要少于stringbuilder,而1000以上stringbuilder优于string

using System;
using System.Text;
using System.Diagnostics;

namespace Teststringbuider
{
    class Program
    {
        static void Main()
        {
            int size = 100;
          
            Console.WriteLine();
            for (int i = 0; i <= 3; i++)
            {
                 Stopwatch watch1 = new Stopwatch();
                 watch1.Start();
                 BuildSB(size);
                 watch1.Stop();
                 Stopwatch watch2 = new Stopwatch();
                 watch2.Start();
                 BuildString(size);
                 watch2.Stop();
                 Console.WriteLine("时间(单位毫秒)创建 StringBuilder " + "对象 有 " + size + " 字符需要的时间: " + watch1.Elapsed);
                 Console.WriteLine("时间(单位毫秒)创建 String  " + "对象有 " + size + " 字符需要的时间: " + watch2.Elapsed);
                 Console.WriteLine();
                 size *= 10;
            }
        }
        //创建StringBuilder连接
        static void BuildSB(int size)
        {
            StringBuilder sbObject = new StringBuilder();
            for (int i = 0; i <= size; i++)
                sbObject.Append("a");
        }
        //创建string连接
        static void BuildString(int size)
        {
            string stringObject = "";
            for (int i = 0; i <= size; i++)
                stringObject += "a";
        }
       
    }
}

原创文章转载请注明出处:云飞扬IT的blog

本文链接: http://www.ajaxcn.net/archives/524

你可能感兴趣的:(StringBuilder)