StringBuilder的替代方案 - 提高性能 [英] Alternative to StringBuilder - To improve Performance

查看:319
本文介绍了StringBuilder的替代方案 - 提高性能的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在迭代一个通用列表,并在一个涉及更多迭代的循环中在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

推荐答案

假设问题是追加本身正在触发调整大小缓冲区然后以更大的初始容量开始为构建器启动。 但是,您应该使用构建器追加调用验证问题,而不是要生成
要插入的字符串的任何逻辑。

Assuming the issue is that the append itself is triggering a resizing of the buffer then start with a bigger initial capacity for the builder.  However you should verify the issue is with the builder append call and not any logic that is generating the string to insert.

可能更好的方法可能是创建一个字符串列表。我假设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的替代方案 - 提高性能的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆