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

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

问题描述

我的三个同事刚刚告诉我,没有理由使用StringBuilder代替使用 + 运算符的连接。换句话说,这很适合一串字符串: myString1 + myString2 + myString3 + myString4 + mySt ...



他们使用的理由是,从.NET 2开始,如果使用 + 操作符,C#编译器将构建相同的IL,就像使用StringBuilder 。



这是我的新闻。是否正确?

解决方案

不,他们不正确。字符串连接创建一个新的字符串,而 StringBuilder 使用可变大小的缓冲区来构建字符串,只创建一个字符串对象,当 ToString()



如果您想进一步了解网络上的字符串连接技术,学科。最着重于在循环中使用不同方法的效率。在这种情况下, StringBuilder 比字符串连接使用 10个或更多字符串的连接,这表示它必须使用与连接不同的方法。



也就是说,如果连接常量字符串值,字符串操作符会更好,因为编译器会将它们考虑在内,如果执行非循环连接,使用运算符会更好,因为它们应该导致对 string.Concat 。 / p>

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...

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?

解决方案

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.

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.

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天全站免登陆