我理解String和StringBuilder之间的区别(StringBuilder是可变的),但两者之间有很大的性能差异吗?

我正在工作的程序有很多case驱动的字符串追加(500+)。使用StringBuilder是更好的选择吗?


当前回答

我已经看到,在StringBuilder的实例上使用EnsureCapacity(int capacity)方法调用,然后再将它用于任何字符串存储,可以显著提高性能。我通常在实例化后的代码行中调用它。它的效果和你这样实例化StringBuilder是一样的:

var sb = new StringBuilder(int capacity);

该调用会提前分配所需的内存,从而在多个Append()操作期间减少内存分配。您必须对需要多少内存做出有根据的猜测,但对于大多数应用程序来说,这应该不会太难。我通常会在内存过多的情况下犯错(我们说的是1k左右)。

其他回答

为了澄清Gillian所说的4弦,如果你有这样的东西:

string a,b,c,d;
 a = b + c + d;

那么使用字符串和加号运算符会更快。这是因为(就像Eric指出的Java一样),它在内部自动使用StringBuilder(实际上,它使用StringBuilder也使用的原语)

但是,如果你正在做的事情接近:

string a,b,c,d;
 a = a + b;
 a = a + c;
 a = a + d;

然后你需要显式地使用一个StringBuilder。. net在这里不会自动创建一个StringBuilder,因为这毫无意义。在每行的末尾,"a"必须是一个(不可变的)字符串,因此它必须在每行上创建和释放一个StringBuilder。为了提高速度,你需要使用相同的StringBuilder,直到你完成构建:

string a,b,c,d;
StringBuilder e = new StringBuilder();
 e.Append(b);
 e.Append(c);
 e.Append(d);
 a = e.ToString();

这个基准测试表明,当组合3个或更少字符串时,常规连接更快。

http://www.chinhdo.com/20070224/stringbuilder-is-not-always-faster/

StringBuilder可以在内存使用方面做出非常显著的改进,特别是在将500个字符串加在一起的情况下。

考虑下面的例子:

string buffer = "The numbers are: ";
for( int i = 0; i < 5; i++)
{
    buffer += i.ToString();
}
return buffer;

内存中发生了什么?创建以下字符串:

1 - "The numbers are: "
2 - "0"
3 - "The numbers are: 0"
4 - "1"
5 - "The numbers are: 01"
6 - "2"
7 - "The numbers are: 012"
8 - "3"
9 - "The numbers are: 0123"
10 - "4"
11 - "The numbers are: 01234"
12 - "5"
13 - "The numbers are: 012345"

通过将这5个数字加到字符串的末尾,我们创建了13个字符串对象!其中12个是无用的!哇!

StringBuilder fixes this problem. It is not a "mutable string" as we often hear (all strings in .NET are immutable). It works by keeping an internal buffer, an array of char. Calling Append() or AppendLine() adds the string to the empty space at the end of the char array; if the array is too small, it creates a new, larger array, and copies the buffer there. So in the example above, StringBuilder might only need a single array to contain all 5 additions to the string-- depending on the size of its buffer. You can tell StringBuilder how big its buffer should be in the constructor.

是的,StringBuilder在对字符串执行重复操作时提供了更好的性能。这是因为所有的更改都是对单个实例进行的,因此它可以节省大量时间,而不是像String那样创建一个新实例。

String Vs Stringbuilder

字符串 系统命名空间下 不可变(只读)实例 当价值发生持续变化时,性能下降 线程安全的 StringBuilder(可变字符串) 在系统。文本名称空间 可变的实例 显示更好的性能,因为对现有实例进行了新的更改

强烈推荐dotnet mob文章:c#中的String Vs StringBuilder。 相关堆栈溢出问题:字符串时的可变性 在c#中没有改变?

以“微优化剧场的悲剧”为例。

作为一般的经验法则,如果我必须设置字符串的值不止一次,或者如果字符串有任何追加,那么它需要是一个字符串构建器。在了解字符串构建器之前,我曾经看到我过去编写的应用程序具有巨大的内存足迹,而且似乎一直在不断增长。将这些程序更改为使用字符串构建器可以显著减少内存使用。现在我对琴弦制造者发誓。