我理解String和StringBuilder之间的区别(StringBuilder是可变的),但两者之间有很大的性能差异吗?
我正在工作的程序有很多case驱动的字符串追加(500+)。使用StringBuilder是更好的选择吗?
我理解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的实例上使用EnsureCapacity(int capacity)方法调用,然后再将它用于任何字符串存储,可以显著提高性能。我通常在实例化后的代码行中调用它。它的效果和你这样实例化StringBuilder是一样的:
var sb = new StringBuilder(int capacity);
该调用会提前分配所需的内存,从而在多个Append()操作期间减少内存分配。您必须对需要多少内存做出有根据的猜测,但对于大多数应用程序来说,这应该不会太难。我通常会在内存过多的情况下犯错(我们说的是1k左右)。
StringBuilder减少了分配和赋值的数量,代价是使用了额外的内存。如果使用得当,它可以完全消除编译器需要一遍又一遍地分配越来越大的字符串,直到找到结果为止。
string result = "";
for(int i = 0; i != N; ++i)
{
result = result + i.ToString(); // allocates a new string, then assigns it to result, which gets repeated N times
}
vs.
String result;
StringBuilder sb = new StringBuilder(10000); // create a buffer of 10k
for(int i = 0; i != N; ++i)
{
sb.Append(i.ToString()); // fill the buffer, resizing if it overflows the buffer
}
result = sb.ToString(); // assigns once
从内存的角度来看,StringBuilder的性能会更好。至于处理,执行时间的差异可以忽略不计。
字符串连接将花费更多。 在Java中,您可以根据需要使用StringBuffer或StringBuilder。 如果您想要一个同步的、线程安全的实现,请使用StringBuffer。这将比字符串连接更快。
如果你不需要同步的或者线程安全的实现,选择StringBuilder。 这将比String连接更快,也比StringBuffer更快,因为它们没有同步开销。
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