字符串与 StringBuilder [英] String vs. StringBuilder
问题描述
我了解 String
和 StringBuilder
之间的区别(StringBuilder
是可变的)但是两者之间的性能差异很大吗?
I understand the difference between String
and StringBuilder
(StringBuilder
being mutable) but is there a large performance difference between the two?
我正在开发的程序有很多大小写驱动的字符串追加(500+).使用 StringBuilder
是更好的选择吗?
The program I’m working on has a lot of case driven string appends (500+). Is using StringBuilder
a better choice?
推荐答案
是的,性能差异很大.请参阅知识库文章如何提高 Visual C# 中的字符串连接性能".
Yes, the performance difference is significant. See the KB article "How to improve string concatenation performance in Visual C#".
我总是尝试先编码以提高清晰度,然后再优化性能.这比反过来做要容易得多!但是,在看到我的应用程序在两者之间的巨大性能差异之后,我现在更仔细地考虑了一下.
I have always tried to code for clarity first, and then optimize for performance later. That's much easier than doing it the other way around! However, having seen the enormous performance difference in my applications between the two, I now think about it a little more carefully.
幸运的是,对您的代码运行性能分析以查看您将时间花在哪里,然后修改它以在需要的地方使用 StringBuilder
相对简单.
Luckily, it's relatively straightforward to run performance analysis on your code to see where you're spending the time, and then to modify it to use StringBuilder
where needed.
这篇关于字符串与 StringBuilder的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!