字符串与StringBuilder的字符串、StringBuilder

2023-09-02 10:15:06 作者:傲娇的野狗

据我了解字符串之间的差异的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#".

我一直都在code为清楚起见先,然后再优化性能。这比周围做其他的方式要容易得多!然而,在看到我的这两个应用程序之间的巨大性能差异,我现在想想多了几分谨慎。

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.

幸运的是,它是相对简单的在你的code运行性能分析,看看你花的时间,然后修改它使用的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.