StringBuilder的VS符号等于concatentation [英] StringBuilder vs ampersand equals concatentation

查看:243
本文介绍了StringBuilder的VS符号等于concatentation的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我被教导,要提高性能VB.NET,我们可以使用StringBuilder的连接字符串。

I was taught that to improve performance in VB.NET, we can use StringBuilder to concatenate strings.

StringBuilder1.Append(string1)
StringBuilder1.Append(string2)

相对于

string1 = string1 & string2

同样,有StringBuilder的超过&放大器性能增益= 串联?

StringBuilder1.Append(string1)
StringBuilder1.Append(string2)

相对于

string1 &= string2

在我的球队更高级的开发者反对使用的StringBuilder。有没有一种方法,以基准这些差异?或者是区别除了在放量的环境中无足轻重?我知道有很多的答案来的StringBuilder与网络等串联,但我无法找到任何具体涉及&安培; =

推荐答案

A和= B 仅仅是一个快捷键 A = A和; b 。因此,他们的速度是相同的。

a &= b is just a shortcut for a = a & b. Therefore their speeds are equal.

的StringBuilder 是串联两个字符串,但是如果你反复追加字符串,它可以更有效地工作,因为它以减少内存使用智能算法不是更快分配和字符串复制操作。

StringBuilder is not faster in concatenating 2 strings, however if you are appending strings repeatedly, it can work more efficiently, because it uses a clever algorithm in order to reduce memory allocations and string copy operations.

在另一方面,一个字符串连接总是创建一个新的字符串,因此每次和复印件每次连续增长的字符串分配新内存。

On the other hand, a string concatenation always creates a new string and therefore allocates new memory each time and copies the successively growing string each time.

a = "hello"
a &= b
a &= c
a &= d
...

这创造和新的字符串每次分配内存。

This creates and allocates memory for new strings each time.

根据埃里克利珀在新的实施,字符串生成器维护一个链表相对较小的阵列,并追加新的数组到列表的末尾,当旧已满。

According to Eric Lippert "In the new implementation, the string builder maintains a linked list of relatively small arrays, and appends a new array onto the end of the list when the old one gets full".

最后一个字符串,然后分配一次(因为现在它的最终长度是已知的),所有的字符串片段复制到它。

The final string is then allocated only once (since now its final length is known) and all the string snippets are copied to it.

内存分配的速度快。当垃圾回收器要收集未使用的内存真正的问题来了。的多个存储器块具有为集,更多的时间花费进行评估,并该方法是更耗时比内存的分配。

Memory allocations are fast. The real problem comes when the garbage collector wants to collect unused memory. The more memory chunks have to be evaluated for collection, the more time it takes and this process is much more time consuming than the allocation of memory.

这篇关于StringBuilder的VS符号等于concatentation的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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