哪里是字符串比一个StringBuilder更有用? [英] Where are strings more useful than a StringBuilder?
问题描述
问题批次已经被问起字符串,字符串建设者和大多数人认为字符串生成器比字符串快之间的差异。我很想知道,如果字符串生成器是太好,为什么字符串是那里?此外,可一些身体给我一个例子,串会比字符串生成更多有用的?
Lot of questions has been already asked about the differences between string and string builder and most of the people suggest that string builder is faster than string. I am curious to know if string builder is too good so why string is there? Moreover, can some body give me an example where string will be more usefull than string builder?
推荐答案
这不是其中的一个情况下,更为有用...
It's not a case of which is more useful...
A 字符串
是字符串
- 一个或多个字符旁边的海誓山盟。如果你想为的变更的的字符串以某种方式,它只会创造更多的字符串,因为他们的的的不可改变 的
A String
is a String
- one or more characters next to eachother. If you want to change a string in someway, it will simply create more strings because they are immutable.
A 的StringBuilder
是它创建的字符串的类。它提供了构造它们没有在存储器创建大量reduntant字符串的手段。最终的结果将永远是一个字符串
。
A StringBuilder
is a class which creates strings. It provides a means of constructing them without creating lots of reduntant strings in memory. The end result will always be a String
.
不要这样做
string s = "my string";
s += " is now a little longer";
或
s = s + " is now longer again";
这将创造的 5 在内存中的字符串(在现实中,见下文)
That would create 5 strings in memory (in reality, see below).
做到这一点:
StringBuilder sb = new StringBuilder();
sb.Append("my string");
sb.Append(" is now a little longer");
sb.Append(" is now longer again");
string s = sb.ToString();
这将创造 1 字符串存储器(再次,见下文)。
That would create 1 string in memory (again, see below).
您可以这样做:
string s = "It is now " + DateTime.Now + ".";
这只是创建 1 字符串在内存中。
This only creates 1 string in memory.
作为一个侧面说明,创建一个的StringBuilder
确实需要一定量的内存反正。作为一个粗略的规则:
As a side-note, creating a StringBuilder
does take a certain amount of memory anyway. As a rough rule of thumb:
- 总是使用
的StringBuilder
如果你在一个循环连接字符串。 - 使用一个
的StringBuilder
如果你连接字符串的4倍以上。
- Always use a
StringBuilder
if you're concatenating strings in a loop. - Use a
StringBuilder
if you're concatenating a string more than 4 times.
这篇关于哪里是字符串比一个StringBuilder更有用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!