C#字符串拼接+连接与Append()方法速度比较闲来无事,为了验证一下+与append()方法拼接字符串速度比较,append方法更快,究竟快多少,在什么样的数量级别用+连接,在什么样的级别要改用append()方法连接字符串,写了一段代码,一测试,结果有点出乎意外。拼交接例子就是连接字符串1,结果发现在拼接10000个1,两者速度不相上下,但到了100000个级别,“+”连接就显得很无力了,居然要了将近40s,很明显,时间与数量并非线性递增关系,然页append()方法依然超快,几乎不要时间(62毫秒)。再测试,在40000级别,“+”连接需时就达1秒左右,append()在10000000(千万级),也只要了750毫秒,只是在页面输出时没有能显示完,挂机了。“+”百万级没敢做了,估计当机。大量字符串拼接时,append()方法明显优于+连接。测试环境:T56002GDDR2IE8VS2008(同时45个进程)前台:“+”连接ADD测试append()方法APP测试%@PageLanguage=C#AutoEventWireup=trueCodeFile=conbineStringTest.aspx.csInherits=test_conbineStringTest%!DOCTYPEhtmlPUBLIC-//W3C//DTDXHTML1.0Transitional//EN==servertitle/title/headbodyformid=form1runat=serverdiv请输入长度asp:TextBoxID=TextBox1runat=server/asp:TextBoxasp:ButtonID=Button2runat=serverText=ADD测试onclick=Button2_Click/asp:ButtonID=Button3runat=serverText=APP测试onclick=Button3_Click/br/spanid=addrunat=server/spanbr/spanid=apprunat=server/span/div/form/body/html后台:usingSystem;usingSystem.Collections.Generic;usingSystem.Linq;usingSystem.Web;usingSystem.Web.UI;usingSystem.Web.UI.WebControls;usingSystem.Text;publicpartialclasstest_conbineStringTest:System.Web.UI.Page{protectedvoidPage_Load(objectsender,EventArgse){}protectedvoidButton2_Click(objectsender,EventArgse){clear();inti=0;if(System.Text.RegularExpressions.Regex.IsMatch(this.TextBox1.Text,@\d+)){intcount=Convert.ToInt32(this.TextBox1.Text);DateTimestartTime=DateTime.Now;stringr=null;for(i=1;i=count;i++){r+=1;if(i%100==0){r+=br/;}}DateTimeendTime=DateTime.Now;this.add.InnerHtml=ADD开始于:+startTime.ToString(yyyy-MM-ddHH:mm:ss.fff)+结束于:+endTime.ToString(yyyy-MM-ddHH:mm:ss.fff)+用时:+DateDiff(endTime,startTime)+br/+r;}else{this.add.InnerHtml=请输入一个数字;}}privatestringDateDiff(DateTimeDateTime1,DateTimeDateTime2){stringdateDiff=null;TimeSpants1=newTimeSpan(DateTime1.Ticks);TimeSpants2=newTimeSpan(DateTime2.Ticks);TimeSpants=ts1.Subtract(ts2).Duration();//dateDiff=ts.Days.ToString()+天//+ts.Hours.ToString()+小时dateDiff=ts.Minutes.ToString()+分钟+ts.Seconds.ToString()+秒+ts.Milliseconds.ToString()+毫秒;returndateDiff;}protectedvoidButton3_Click(objectsender,EventArgse){clear();inti=0;intcount=Convert.ToInt32(this.TextBox1.Text);DateTimestartTime=DateTime.Now;StringBuildersb=newStringBuilder();for(i=1;i=count;i++){sb.Append(1);if(i%100==0){sb.Append(br);}}DateTimeendTime=DateTime.Now;this.app.InnerHtml=APP开始于:+startTime.ToString(yyyy-MM-ddHH:mm:ss.fff)+结束于:+endTime.ToString(yyyy-MM-ddHH:mm:ss.fff)+用时:+DateDiff(endTime,startTime)+br/+sb.ToString();}protectedvoidclear(){this.app.InnerHtml=null;this.add.InnerHtml=null;}}