(41)StringBuilder is NOT the answer for all string concatenation scenarios; String.Join could beios
招数41:app
StringBuilder不适用于全部字符串链接的场景;String.Join多是oop
Yes, if you are in a loop and adding to a string, then a StringBuilder *could* be most appropriate. However, the overhead of spinning up a StringBuilder instance makes the following pretty dumb:
是的,若是你是在一个循环中并添加到一个字符串,那么StringBuilder多是最适合的。然而,建立一个StringBuilder实例的开销让下面的代码至关愚蠢的。ui
var sb = new StringBuilder(); sb.Append(“Frankly, this is “); sb.Append(notMoreEfficient); sb.Append(“. Even if you are in a loop.”); var whyNotJustConcat = sb.ToString();
Instead, use String.Join, which is typically more performant than spinning up a StringBuilder instance for a limited number of strings. It’s my go-to concat option:
相反,对于一个有限数量的字符串使用String.Join比建立一个StringBuilder实例一般是更具表现力的。这是我首选字符串链接方式:this
string key = String.Join(“ “, new String[] { “This”, “is”, “a”, “much”, “better”, solution, “.”});
The first variable of " " can just be set to "" when you don’t want a delimiter.
当你不想要一个分隔符时候,第一个变量的“ ”能够被设置为“”。spa
For loops that do a lot of, er, looping, sure, use a StringBuilder.
循环中那么作就多余了,嗯,循环,固然是用StringBuilder。code
Just don’t assume it’s the de facto solution in all, or even the majority of cases. My rule of thumb is to add strings together when I’ve got one to five of them (likewise with String.Format if it helps with legibility). For most other cases, I tend towards String.Join. Only when dealing with a loop that isn’t limited to about 10 iterations, especially one that really lets rip, do I spin up a StringBuilder.
只要不认为他不是全部的解决方案,甚至大多数状况下。个人原则是当我有1到5个字符链接的时候(一样是String.Format若是他有助于易读性) 对于其余大多数状况下,我倾向于String.Join。只有当处理一个并不限于10次迭代的循环,特别是...,我会使用StringBuilder。orm