修改了下上次写过的一篇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

相关文章:

  • 2022-01-12
  • 2022-01-20
  • 2021-11-05
  • 2021-05-08
  • 2021-08-25
  • 2021-05-23
  • 2022-02-13
猜你喜欢
  • 2022-12-23
  • 2021-12-14
  • 2021-05-21
  • 2022-12-23
  • 2021-05-03
  • 2021-12-01
  • 2021-08-14
相关资源
相似解决方案