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

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


当前回答

StringBuilder更适合从许多非常量值构建字符串。

If you're building up a string from a lot of constant values, such as multiple lines of values in an HTML or XML document or other chunks of text, you can get away with just appending to the same string, because almost all compilers do "constant folding", a process of reducing the parse tree when you have a bunch of constant manipulation (it's also used when you write something like int minutesPerYear = 24 * 365 * 60). And for simple cases with non-constant values appended to each other, the .NET compiler will reduce your code to something similar to what StringBuilder does.

但是当你的append不能被编译器简化为更简单的东西时,你将需要一个StringBuilder。正如fizch所指出的,这更有可能发生在循环内部。

其他回答

在. net中,StringBuilder仍然比追加字符串快。我很确定在Java中,它们只是在附加字符串时在底层创建了一个StringBuffer,所以没有真正的区别。我不确定为什么他们还没有在。net中这样做。

如果你要做很多字符串连接,使用StringBuilder。当您连接一个String时,每次都会创建一个新的String,这会占用更多的内存。

Alex

这个基准测试表明,当组合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.

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

是的,性能差异是显著的。请参阅KB文章“如何在Visual c#中提高字符串连接性能”。

我总是试着先编写清晰的代码,然后再优化性能。这比反过来做要容易得多!但是,看到了两者在我的应用程序中的巨大性能差异后,我现在更仔细地考虑了一下。

幸运的是,在代码上运行性能分析相对简单,可以看到您在哪些地方花费了时间,然后在需要的地方修改它以使用StringBuilder。