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

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


当前回答

为了澄清Gillian所说的4弦,如果你有这样的东西:

string a,b,c,d;
 a = b + c + d;

那么使用字符串和加号运算符会更快。这是因为(就像Eric指出的Java一样),它在内部自动使用StringBuilder(实际上,它使用StringBuilder也使用的原语)

但是,如果你正在做的事情接近:

string a,b,c,d;
 a = a + b;
 a = a + c;
 a = a + d;

然后你需要显式地使用一个StringBuilder。. net在这里不会自动创建一个StringBuilder,因为这毫无意义。在每行的末尾,"a"必须是一个(不可变的)字符串,因此它必须在每行上创建和释放一个StringBuilder。为了提高速度,你需要使用相同的StringBuilder,直到你完成构建:

string a,b,c,d;
StringBuilder e = new StringBuilder();
 e.Append(b);
 e.Append(c);
 e.Append(d);
 a = e.ToString();

其他回答

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

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

以“微优化剧场的悲剧”为例。

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

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.

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

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

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