我有一种情况需要连接几个字符串以形成一个类的 id。基本上,我只是在列表中循环以获取对象的 ToString 值,然后将它们连接起来。
foreach (MyObject o in myList)
result += o.ToString();
该列表预计不会超过 5 个元素(尽管它可以,但这是非常非常边缘的情况)并且通常会有 1 到 3 个元素,通常只有一个或两个元素。
保持串联或使用 StringBuilder 哪个性能更好?
StringBuilder bld = new StringBuilder()
foreach (MyObject o in myList)
bld.Append(o.ToString());
对于大多数常见情况,我不确定创建 StringBuilder 是否会比标准串联花费更多时间。
这是惰性的,列表中的项目一旦创建就不会改变,因此 id 在调用时被惰性构造一次。
作为旁注...我应该使用固定数组而不是列表吗?如果我这样做,我会得到任何性能或内存改进吗? (无论如何,列表仅用作 IEnumerable)
这个问题的更普遍的观点可能是,有多少字符串足以停止连接并开始构建?
我是否应该费心测试这个场景?
if (myList.Count > 4)
ConcatWithStringBuilder(myList);
最佳答案
通常的答案是字符串连接对于 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();
关于c# - 字符串连接与字符串生成器。表现,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1612797/