在什么时候使用StringBuilder中变得无足轻重或开销? [英] At what point does using a StringBuilder become insignificant or an overhead?

查看:216
本文介绍了在什么时候使用StringBuilder中变得无足轻重或开销?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

最近我发现自己使用StringBuilder的所有字符串连接,有大有小,但在最近的一次性能测试中我换了一个同事的的 stringOut =字符串1 +。字符串2 的风格串联(正在使用的10000倍+循环与StringBuilder的每一次被newed)为一个StringBuilder只是为了看看有什么区别它将使一个小的连接。

Recently I have found myself using StringBuilder for all string concatenations, big and small, however in a recent performance test I swapped out a colleague's stringOut = string1 + "." string2 style concatenation (being used in a 10000x + loop with the StringBuilder being newed each time) for a StringBuilder just to see what difference it would make in a minor concatenation.

我发现,在性能测试多次运行,这种变化既无显着高于或低于无论串联或StringBuilder的(重申,这是对的的串联)。

I found, over many runs of the performance test, the change was both insignificantly higher or lower regardless of concatenation or StringBuilder (restating this was for small concatenations).

在什么时候了newing了'一个StringBuilder对象的抵消使用它的好处?

At what point does the 'newing up' of a StringBuilder object negate the benefits of using one?

推荐答案

这是我所遵循的是规则 -

The rule that I follow is -

使用StringBuilder当串联的数量是未知在编译时。

Use a StringBuilder when the number of concatenations is unknown at compile time.

那么,在你的情况下,每个StringBuilder的只是附加了几下,然后被丢弃。这是不是真的一样像

So, in your case each StringBuilder was only appending a few times and then being discarded. That isn't really the same as something like

string s = String.Empty;
for (int i = 0; i < 10000; ++i)
{
    s += "A";
}

如果使用一个StringBuilder将大大提高性能,因为否则你将被不断分配新的内存。

Where using a StringBuilder would drastically improve performance because you would otherwise be constantly allocating new memory.

这篇关于在什么时候使用StringBuilder中变得无足轻重或开销?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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