C# 何时使用 StringBuilder?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/1825781/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
When to use StringBuilder?
提问by Shiraz Bhaiji
I understand the benefits of StringBuilder.
我了解 StringBuilder 的好处。
But if I want to concatenate 2 strings, then I assume that it is better (faster) to do it without StringBuilder. Is this correct?
但是如果我想连接 2 个字符串,那么我认为没有 StringBuilder 会更好(更快)。这样对吗?
At what point (number of strings) does it become better to use StringBuilder?
在什么时候(字符串的数量)使用 StringBuilder 会变得更好?
采纳答案by Alex Bagnolini
I warmly suggest you to read The Sad Tragedy of Micro-Optimization Theater, by Jeff Atwood.
我强烈建议您阅读杰夫·阿特伍德 (Jeff Atwood) 所著的《微优化剧院的悲惨悲剧》。
It treats Simple Concatenation vs. StringBuilder vs. other methods.
它处理 Simple Concatenation 与 StringBuilder 与其他方法。
Now, if you want to see some numbers and graphs, follow the link ;)
现在,如果您想查看一些数字和图表,请点击链接;)
回答by Matt Wrock
A single concatenation is not worth using a StringBuilder. I've typically used 5 concatenations as a rule of thumb.
单个串联不值得使用 StringBuilder。我通常使用 5 个连接作为经验法则。
回答by Bobby
Not really...you should use StringBuilder if you concatenate largestrings or you have many concatenations, like in a loop.
不是真的......如果你连接大字符串或者你有很多连接,比如在循环中,你应该使用 StringBuilder 。
回答by Konrad Rudolph
But if I want to concatenate 2 strings, then I assume that it's better and faster to do so without StringBuilder. Is this correct?
但是如果我想连接 2 个字符串,那么我认为在没有 StringBuilder 的情况下这样做会更好更快。这样对吗?
Yes. But more importantly, it is vastly more readableto use a vanilla String
in such situations. Using it in a loop, on the other hand, makes sense and can also be as readable as concatenation.
是的。但更重要的是,在这种情况下使用 vanilla更具可读性String
。另一方面,在循环中使用它是有意义的,并且也可以像串联一样可读。
I'd be wary of rules of thumb that cite specific numbers of concatenation as a threshold. Using it in loops (and loops only) is probably just as useful, easier to remember and makes more sense.
我会警惕那些引用特定连接数作为阈值的经验法则。在循环(和仅循环)中使用它可能同样有用,更容易记住并且更有意义。
回答by Peter
But if I want to concatinate 2 strings, then I assume that it is better (faster) to do it without StringBuilder. Is this correct?
但是如果我想连接 2 个字符串,那么我认为没有 StringBuilder 会更好(更快)。这样对吗?
That is indeed correct, you can find why exactly explained very well on :
这确实是正确的,您可以在以下内容中找到确切解释的原因:
http://www.yoda.arachsys.com/csharp/stringbuilder.html
http://www.yoda.arachsys.com/csharp/stringbuilder.html
Summed up : if you can concatinate strings in one go like
总结:如果你可以一次性连接字符串
var result = a + " " + b + " " + c + ..
you are better off without StringBuilder for only on copy is made (the length of the resulting string is calculated beforehand.);
最好不要使用 StringBuilder,因为只进行复制(预先计算结果字符串的长度。);
For structure like
对于结构如
var result = a;
result += " ";
result += b;
result += " ";
result += c;
..
new objects are created each time, so there you should consider StringBuilder.
每次都会创建新对象,因此您应该考虑 StringBuilder。
At the end the article sums up these rules of thumb :
文章最后总结了这些经验法则:
Rules Of Thumb
So, when should you use StringBuilder, and when should you use the string concatenation operators?
Definitely use StringBuilder when you're concatenating in a non-trivial loop - especially if you don't know for sure (at compile time) how many iterations you'll make through the loop. For example, reading a file a character at a time, building up a string as you go using the += operator is potentially performance suicide.
Definitely use the concatenation operator when you can (readably) specify everything which needs to be concatenated in one statement. (If you have an array of things to concatenate, consider calling String.Concat explicitly - or String.Join if you need a delimiter.)
Don't be afraid to break literals up into several concatenated bits - the result will be the same. You can aid readability by breaking a long literal into several lines, for instance, with no harm to performance.
If you need the intermediate results of the concatenation for something other than feeding the next iteration of concatenation, StringBuilder isn't going to help you. For instance, if you build up a full name from a first name and a last name, and then add a third piece of information (the nickname, maybe) to the end, you'll only benefit from using StringBuilder if you don't need the (first name + last name) string for other purpose (as we do in the example which creates a Person object).
If you just have a few concatenations to do, and you really want to do them in separate statements, it doesn't really matter which way you go. Which way is more efficient will depend on the number of concatenations the sizes of string involved, and what order they're concatenated in. If you really believe that piece of code to be a performance bottleneck, profile or benchmark it both ways.
经验法则
那么,什么时候应该使用 StringBuilder,什么时候应该使用字符串连接运算符?
当您在一个非平凡的循环中进行连接时,一定要使用 StringBuilder - 特别是如果您不确定(在编译时)您将通过循环进行多少次迭代。例如,一次读取一个文件,使用 += 运算符构建一个字符串,这可能是性能自杀。
当您可以(可读地)指定需要在一个语句中连接的所有内容时,一定要使用连接运算符。(如果您有一系列要连接的内容,请考虑显式调用 String.Concat - 如果需要分隔符,请考虑调用 String.Join。)
不要害怕将文字分解成几个串联的位 - 结果将是相同的。例如,您可以通过将长文字分成几行来提高可读性,而不会对性能造成损害。
如果您需要连接的中间结果而不是提供下一次连接迭代,StringBuilder 不会帮助您。例如,如果您从一个名字和一个姓氏建立一个全名,然后在最后添加第三条信息(可能是昵称),那么只有在您不这样做的情况下才可以从使用 StringBuilder 中受益需要(名字 + 姓氏)字符串用于其他目的(就像我们在创建 Person 对象的示例中所做的那样)。
如果您只需要执行几个连接,并且您真的想在单独的语句中执行它们,那么走哪条路并不重要。哪种方式更有效将取决于所涉及的字符串大小的串联次数,以及它们串联的顺序。如果您真的认为那段代码是性能瓶颈,请以两种方式对其进行配置文件或基准测试。
回答by Victor Hurdugaci
System.String is an immutable object - it means that whenever you modify its content it will allocate a new string and this takes time (and memory?). Using StringBuilder you modify the actual content of the object without allocating a new one.
System.String 是一个不可变对象 - 这意味着无论何时修改其内容,它都会分配一个新字符串,这需要时间(和内存?)。使用 StringBuilder 可以修改对象的实际内容,而无需分配新内容。
So use StringBuilder when you need to do many modifications on the string.
因此,当您需要对字符串进行多次修改时,请使用 StringBuilder。
回答by LukeH
There's no definitive answer, only rules-of-thumb. My own personal rules go something like this:
没有绝对的答案,只有经验法则。我个人的规则是这样的:
- If concatenating in a loop, always use a
StringBuilder
. - If the strings are large, always use a
StringBuilder
. - If the concatenation code is tidy and readable on the screen then it's probably ok.
If it isn't, use aStringBuilder
.
- 如果在循环中连接,请始终使用
StringBuilder
. - 如果字符串很大,请始终使用
StringBuilder
. - 如果串联代码在屏幕上整洁且可读,那么可能没问题。
如果不是,请使用StringBuilder
.
回答by o.k.w
I don't think there's a fine line between when to use or when not to. Unless of course someone performed some extensive testings to come out with the golden conditions.
我认为何时使用或何时不使用之间没有明确的界限。当然,除非有人进行了一些广泛的测试以得出黄金条件。
For me, I will not use StringBuilder if just concatenating 2 huge strings. If there's loop with an undeterministic count, I'm likely to, even if the loop might be small counts.
对我来说,如果只是连接 2 个巨大的字符串,我不会使用 StringBuilder。如果存在具有不确定计数的循环,我可能会这样做,即使循环可能是小计数。
回答by wisty
As long as you can physically type the number of concatenations (a + b + c ...) it shouldn't make a big difference. N squared (at N = 10) is a 100X slowdown, which shouldn't be too bad.
只要您可以实际输入连接的数量 (a + b + c ...),它就不会有太大的不同。N 平方(N = 10)是 100 倍的减速,这应该不会太糟糕。
The big problem is when you are concatenating hundreds of strings. At N=100, you get a 10000X times slowdown. Which is pretty bad.
最大的问题是当您连接数百个字符串时。在 N=100 时,您会得到 10000 倍的减速。这很糟糕。
回答by Russell Steen
To paraphrase
转述
Then shalt thou count to three, no more, no less. Three shall be the number thou shalt count, and the number of the counting shall be three. Four shalt thou not count, neither count thou two, excepting that thou then proceed to three. Once the number three, being the third number, be reached, then lobbest thou thy Holy Hand Grenade of Antioch
然后你数到三,不多也不少。三是你要数的数,数的数是三。四你不要数,你也不要数二,除非你继续到三。一旦达到第三个数字,即第三个数字,然后向你挥舞你的安条克圣手手榴弹
I generally use string builder for any block of code which would result in the concatenation of three or more strings.
我通常将字符串生成器用于任何会导致三个或更多字符串连接的代码块。