字符串连接与字符串生成器。性能

字符串连接与字符串生成器。性能,第1张

字符串连接字符串生成器。性能

通常的答案是,字符串连接对于4到8个字符串更有效。这取决于您阅读的博客。

不要编写测试来决定使用哪种方法。如果您不确定它是否会超出魔术限制,则只需使用StringBuilder。

运行以下代码以亲自查看结果:

const int sLen=30, Loops=5000;DateTime sTime, eTime;int i;string sSource = new String('X', sLen);string sDest = "";// // Time string concatenation.// sTime = DateTime.Now;for(i=0;i<Loops;i++) sDest += sSource;eTime = DateTime.Now;Console.WriteLine("Concatenation took " + (eTime - sTime).TotalSeconds + " seconds.");// // Time StringBuilder.// sTime = DateTime.Now;System.Text.StringBuilder sb = new System.Text.StringBuilder((int)(sLen * Loops * 1.1));for(i=0;i<Loops;i++) sb.Append(sSource);sDest = sb.ToString();eTime = DateTime.Now;Console.WriteLine("String Builder took " + (eTime - sTime).TotalSeconds + " seconds.");// // Make the console window stay open// so that you can see the results when running from the IDE.// Console.WriteLine();Console.Write("Press Enter to finish ... ");Console.Read();

参考
http://support.microsoft.com/kb/306822



欢迎分享,转载请注明来源:内存溢出

原文地址:https://54852.com/zaji/4934244.html

(0)
打赏 微信扫一扫微信扫一扫 支付宝扫一扫支付宝扫一扫
上一篇 2022-11-13
下一篇2022-11-12

发表评论

登录后才能评论

评论列表(0条)

    保存