是否字符串连接就使用StringBuilder内部? [英] Does string concatenation use StringBuilder internally?

查看:136
本文介绍了是否字符串连接就使用StringBuilder内部?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的同事刚刚三告诉我,我们没有理由到位级联使用StringBuilder的使用 + 运营商。换句话说,这是细跟一堆字符串做: myString1 + myString2 + myString3 + myString4 +神秘岛...

Three of my coworkers just told me that there's no reason to use a StringBuilder in place of concatenation using the + operator. In other words, this is fine to do with a bunch of strings: myString1 + myString2 + myString3 + myString4 + mySt...

这是他们使用的理由是,因为.NET 2,C#编译器将建立同样的IL如果使用 + 运营商,如果你使用一个StringBuilder

The rationale that they used was that since .NET 2, the C# compiler will build the same IL if you use the + operator as if you used a StringBuilder.

这是消息给我。他们是正确的吗?

This is news to me. Are they correct?

推荐答案

没有,他们是不正确的。字符串连接创建一个新的字符串 的StringBuilder 使用可变大小的缓冲区建立字符串,只有创造一个字符串对象时的 的ToString() 是调用。

No, they are not correct. String concatenation creates a new string whereas StringBuilder uses a variable size buffer to build the string, only creating a string object when ToString() is called.

有对字符串连接技术在互联网上许多讨论,如果你想就这个问题进行读取。大多数循环使用时,注重的不同方法的效率。在这种情况下, 的StringBuilder 快过使用字符串运营商10个或更多的字符串串联字符串连接,这应该表明它必须是使用比串联不同的方法。

There are many discussions on string concatenation techniques all over the Internet if you would like to read further on the subject. Most focus on the efficiency of the different methods when used in loops. In that scenario, StringBuilder is faster over string concatenation using string operators for concatenations of 10 or more strings, which should indicate that it must be using a different method than the concatenation.

这是说,如果你串联常量字符串值,该字符串操作会更好,因为编译器会因素他们走,如果你的执行非循环串联,利用运营商将更好,他们应该导致对的 string.Concat

That said, if you're concatenating constant string values, the string operators will be better because the compiler will factor them away, and if your performing non-looped concatenation, using the operators will be better as they should result in a single call to string.Concat.

这篇关于是否字符串连接就使用StringBuilder内部?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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