(41)StringBuilder is NOT the answer for all string concatenation scenarios; String.Join could be
招数41:
StringBuilder不适用于所有字符串连接的场景;String.Join可能是
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实例的开销让下面的代码相当愚蠢的。
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实例通常是更具表现力的。这是我首选字符串连接方式:
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.
当你不想要一个分隔符时候,第一个变量的“ ”可以被设置为“”。For loops that do a lot of, er, looping, sure, use a StringBuilder.
循环中那么做就多余了,嗯,循环,当然是用StringBuilder。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。