C# 简单测试string和StringBuilder

测试代码如下:

  class Program
  {
    static void Main(string[] args)
    {
      string strText = "Hello from all the guys at Wrox Press. ";
      strText += "We do hope you enjoy this book as much as we enjoyed writing it.";
      Stopwatch time1 = new Stopwatch();
      time1.Start();
      for (int j = 0; j < 1000000; j++)
        for (int i = 'z'; i <= 'a'; i--)
        {
          char oldChar = (char)i;
          char newChar = (char)(i + 1);
          strText.Replace(oldChar, newChar);
        }
      for (int j = 0; j < 1000000; j++)
        for (int i = 'Z'; i <= 'A'; i--)
        {
          char oldChar = (char)i;
          char newChar = (char)(i + 1);
          strText.Replace(oldChar, newChar);
        }
      time1.Stop();
      double totalSeconds1 = time1.Elapsed.TotalMilliseconds;

      StringBuilder sbText = new StringBuilder("Hello from all the guys at Wrox Press. ");
      sbText.Append("We do hope you enjoy this book as much as we enjoyed writing it.");

      Stopwatch time2 = new Stopwatch();
      time2.Start();
      for (int j = 0; j < 1000000; j++)
        for (int i = 'z'; i <= 'a'; i--)
        {
          char oldChar = (char)i;
          char newChar = (char)(i + 1);
          sbText.Replace(oldChar, newChar);
        }
      for (int j = 0; j < 1000000; j++)
        for (int i = 'Z'; i <= 'A'; i--)
        {
          char oldChar = (char)i;
          char newChar = (char)(i + 1);
          sbText.Replace(oldChar, newChar);
        }
      time2.Stop();
      double totalSeconds2 = time2.Elapsed.TotalMilliseconds;

      Console.WriteLine("string用时是:       {0:F20}毫秒", totalSeconds1);
      Console.WriteLine("StringBuilder用时是:{0:F20}毫秒", totalSeconds2);
      Console.ReadKey();
    }
  }

结果:

posted @ 2012-04-21 20:46  wouldguan  阅读(277)  评论(0)    收藏  举报