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

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


当前回答

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

eg.

StringBuilder sb = new StringBuilder(50);

其他回答

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

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

eg.

StringBuilder sb = new StringBuilder(50);

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

var sb = new StringBuilder(int capacity);

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

一个简单的例子来演示使用String连接和StringBuilder在速度上的差异:

System.Diagnostics.Stopwatch time = new Stopwatch();
string test = string.Empty;
time.Start();
for (int i = 0; i < 100000; i++)
{
    test += i;
}
time.Stop();
System.Console.WriteLine("Using String concatenation: " + time.ElapsedMilliseconds + " milliseconds");

结果:

使用字符串串联:15423毫秒

StringBuilder test1 = new StringBuilder();
time.Reset();
time.Start();
for (int i = 0; i < 100000; i++)
{
    test1.Append(i);
}
time.Stop();
System.Console.WriteLine("Using StringBuilder: " + time.ElapsedMilliseconds + " milliseconds");

结果:

使用StringBuilder: 10毫秒

结果,第一次迭代花费了15423毫秒,而使用StringBuilder的第二次迭代花费了10毫秒。

在我看来,使用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