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

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


当前回答

The performance of a concatenation operation for a String or StringBuilder object depends on how often a memory allocation occurs. A String concatenation operation always allocates memory, whereas a StringBuilder concatenation operation only allocates memory if the StringBuilder object buffer is too small to accommodate the new data. Consequently, the String class is preferable for a concatenation operation if a fixed number of String objects are concatenated. In that case, the individual concatenation operations might even be combined into a single operation by the compiler. A StringBuilder object is preferable for a concatenation operation if an arbitrary number of strings are concatenated; for example, if a loop concatenates a random number of strings of user input.

来源:MSDN

其他回答

StringBuilder is probably preferable. The reason is that it allocates more space than currently needed (you set the number of characters) to leave room for future appends. Then those future appends that fit in the current buffer don't require any memory allocation or garbage collection, which can be expensive. In general, I use StringBuilder for complex string concatentation or multiple formatting, then convert to a normal String when the data is complete, and I want an immutable object again.

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

Alex

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

我的方法一直是在连接4个或更多字符串时使用StringBuilder 或 当我不知道有多少串联会发生。

好的性能相关文章在这里

除了前面的答案,当我想到这样的问题时,我总是做的第一件事是创建一个小型测试应用程序。在这个应用程序中,为这两种情况执行一些计时测试,看看哪个更快。

恕我直言,添加500+字符串条目绝对应该使用StringBuilder。