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

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


当前回答

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

其他回答

使用字符串进行连接会导致运行时复杂度达到O(n^2)的量级。

如果使用StringBuilder,需要复制的内存就会少得多。使用StringBuilder(int capacity),如果您可以估计最终字符串的大小,则可以提高性能。即使不精确,也可能只需要将StringBuilder的容量增加几倍,这也有助于提高性能。

从内存的角度来看,StringBuilder的性能会更好。至于处理,执行时间的差异可以忽略不计。

String和StringBuilder实际上都是不可变的,StringBuilder内置了缓冲区,允许更有效地管理其大小。当StringBuilder需要调整大小时,就是在堆上重新分配它的时候。默认情况下,它的大小为16个字符,您可以在构造函数中设置此值。

eg.

StringBuilder sb = new StringBuilder(50);

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更快,如果你有超过4个字符串,你需要附加在一起。此外,它可以做一些很酷的事情,如AppendLine。