小新的技术天地

Make It Works !

博客园 首页 新随笔 联系 订阅 管理
做了一个小测试,
按照beautyispower原来的代码:
using System;
using System.Text;

namespace Test
{
public class TestApp
{
  
public static void Main( string[] args )
  
{
   
int intTimeUsed=0;
   
int intCount=0;
   
int intMaxCount=50000;
   
string strTest=string.Empty;
   StringBuilder sbTest
=new StringBuilder(intMaxCount);
   
   
   Console.WriteLine(
"正在使用StringBuilder做字符串相加。");
   intTimeUsed
=Environment.TickCount;
   
while(intCount<intMaxCount)
   
{
    intCount
++;
    sbTest.Append(
"a");
   }

   intTimeUsed
=Environment.TickCount-intTimeUsed;
   Console.WriteLine(
"结束使用StringBuilder做字符串相加。");
   Console.WriteLine(
"用时{0}毫秒",intTimeUsed);
   
   intCount
=0;
   Console.WriteLine(
"开始使用string做字符串相加。");
   intTimeUsed
=Environment.TickCount;
   
while(intCount<intMaxCount)
   
{
    intCount
++;
    strTest
+="a";
   }

   intTimeUsed
=Environment.TickCount-intTimeUsed;
   Console.WriteLine(
"结束使用string做字符串相加。");
   Console.WriteLine(
"用时{0}毫秒",intTimeUsed);


  }

}
  
}


StringBuilder是0毫秒,String大概是5500毫秒左右
把原码中的strTest+="a";改成了strTest =String.Intern(strTest) + "a";
StringBuilder好像变慢了,有时候是0毫秒,有时候是15-16毫秒,
String变快了,稳定在2260左右。

不是很明白其中的原因,还请各位分析指导。

注:此文引用beautyispower在比较StringBuilder string 中的代码
posted on 2004-10-29 19:14  小新0574  阅读(970)  评论(4编辑  收藏  举报