我理解String和StringBuilder之间的区别(StringBuilder是可变的),但两者之间有很大的性能差异吗?
我正在工作的程序有很多case驱动的字符串追加(500+)。使用StringBuilder是更好的选择吗?
我理解String和StringBuilder之间的区别(StringBuilder是可变的),但两者之间有很大的性能差异吗?
我正在工作的程序有很多case驱动的字符串追加(500+)。使用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.
其他回答
一个简单的例子来演示使用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更快,快得多。
StringBuilder是可取的,如果你正在做多个循环,或分叉在你的代码传递…然而,对于PURE性能,如果你可以使用SINGLE字符串声明,那么性能就会更好。
例如:
string myString = "Some stuff" + var1 + " more stuff"
+ var2 + " other stuff" .... etc... etc...;
更有表现力吗
StringBuilder sb = new StringBuilder();
sb.Append("Some Stuff");
sb.Append(var1);
sb.Append(" more stuff");
sb.Append(var2);
sb.Append("other stuff");
// etc.. etc.. etc..
在这种情况下,可以认为StringBuild更易于维护,但性能并不比单个字符串声明更好。
但是十有八九……使用字符串构建器。
另一方面:string + var也比string的性能更好。格式方法(通常)在内部使用StringBuilder(如果有疑问…检查反射器!)
字符串连接将花费更多。 在Java中,您可以根据需要使用StringBuffer或StringBuilder。 如果您想要一个同步的、线程安全的实现,请使用StringBuffer。这将比字符串连接更快。
如果你不需要同步的或者线程安全的实现,选择StringBuilder。 这将比String连接更快,也比StringBuffer更快,因为它们没有同步开销。
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。