问题描述
我正在迭代一个通用列表,并在一个涉及更多迭代的循环中在stringbuilder中附加文本。我正面临性能问题 - 它需要更多时间。
I'm iterating a generic list and appending text in stringbuilder from a loop which involves more iterations.I'm facing a performance issue- its taking more time .
任何人都可以建议我在c#中以任何替代方式更快地附加文本。
任何帮助高度赞赏!!
Can anyone suggest me any alternative in c# to append text in faster way.
Any help highly appreciated!!
Rajesh Yesurajan
Rajesh Yesurajan
推荐答案
可能更好的方法可能是创建一个字符串列表。我假设perf问题不是创建字符串,而是将它们插入到列表中。一旦你有了想要追加的所有字符串,那么使用String.Join到
将它们连接成一个字符串。如果perf问题严格依赖于字符串构建器缓冲区的持续调整大小,那么这将消除该问题。你仍然有分配,但希望不经常。当然我从来没有看过底层实现
但是String.Join可能会使用StringBuilder。但可以对其进行优化以预先计算容量,以避免重新分配缓冲区的开销。
A potentially better approach might be to create a list of strings. I assume that the perf issue isn't with the creation of the strings so insert them into a list instead. Once you have all the strings you want to append then use String.Join to join them into a single string. If the perf issue is strictly with the continual resizing of the string builder buffer then this would remove that issue. You still have allocations but hopefully not as often. Of course I've never looked at the underlying implementation but it is possible String.Join is using StringBuilder under the hood. But it may be optimized to pre-calculate the capacity to avoid the overhead of reallocating the buffer.
这篇关于StringBuilder的替代方案 - 提高性能的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!