引用:
清空StringBuilder的三种方法及效率
大家知道对于字符串频繁拼接是使用stringbuilder.Append方法比使用string+=方法效率高很多,但有时需要清空stringbuilSEO靠我der时却不知道怎么清空,因为它没有clear或empty的方法。那用什么方法呢?在网上搜了一下大概一下三种方法。
1、Delete
例:
StringBuilder val = new StringBuiSEO靠我lder();val.Append("....");val.delete(0,val.length());//清空2、Replace
StringBuilder val = new StringBuilSEO靠我der();val.Append("....");sb.replace(0,sb.length(),"");//清空3、Length
StringBuilder val = new StringBuilSEO靠我der();val.Append("....");sb.setLength(0);//清空对于这三种方法的效率简单做了一下测试,测了三次求的平均值
测试方法:
DateTime dt = DateTimeSEO靠我.Now;
const int testNum = 1000000;
StringBuilder strbuilder = new StringBuilder();
for (int i = 0; i < SEO靠我testNum; i++)
{
strbuilder.Append("test");
strbuilder.Remove(0,strbuilder.Length);
}
Console.WriteLine("RSEO靠我semove:"+(DateTime.Now - dt).Ticks);
第一种用时间:366687
第二种用时间:1186734
第三种用时间:180010
可见还是使用length方法比较效率。
网站备案号:浙ICP备17034767号-2