string类与StringBuilder类性能比较

我们都知道StringBuilder的性能要比string类,是否具体测试过呢,我这里就给出这个程序供测试,一个是Timing类,用来计算时间的。另外一个类就是分别建立string,和stringbuider 类建立100,1000,10000,100000字符连接进行比较。

using System;
using System.Diagnostics;

namespace DataStruct7
{
   public class Timing
    {
        TimeSpan duration;//时间差
        public Timing()
        {
            duration = new TimeSpan(0);
        }
        //开始时间
        public void stopTime()
        {
            duration = Process.GetCurrentProcess().TotalProcessorTime;
        }
       //终止时间

        public void startTime()
        {
            GC.Collect();
            GC.WaitForPendingFinalizers();
        }
       //返回结果
        public TimeSpan Result()
        {
            return duration;
        }
    }
}

另外个类

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

namespace DataStruct7
{
    class Program
    {
        static void Main()
        {
            int size = 100;
            Timing timeSB = new Timing();
            Timing timeST = new Timing();

            Console.WriteLine();
            for (int i = 0; i <= 3; i++)
            {
                timeSB.startTime();
                BuildSB(size);
                timeSB.stopTime();
                timeST.startTime();
                BuildString(size);
                timeST.stopTime();
                Console.WriteLine("时间(单位毫秒)创建 StringBuilder " + "对象 有 " + size + " 字符需要的时间: " + timeSB.Result().TotalMilliseconds);
                Console.WriteLine("时间(单位毫秒)创建 String  " + "对象有 " + size + " 字符需要的时间: " + timeST.Result().TotalMilliseconds);
                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";
        }

    }
}

来源:http://www.ajaxcn.net/archives/499

posted @ 2009-11-01 22:30  云飞扬IT  阅读(461)  评论(5编辑  收藏  举报