Select string and StringBuilder in C #

Source: Internet
Author: User

In many cases, StringBuilder is faster and faster than string concatenation.

The fact is that StringBuilder is faster than string because the intermediate object is generated during string concatenation and eventually garbage is generated.
For example:
String str = "";
Str + = "B ";
Str + = "c ";
The final result is "abc", but the second line produces "AB", which is only an intermediate object and garbage. Using StringBuilder will avoid the generation of such intermediate objects.

What if I write this?
String str = ""
+ "B"
+ "C ";

Will this be slower than StringBuilder? Absolutely not!
Not to mention that string concatenation of such constants will be processed during compilation. Even if "B" and "c" are not constants or variables, the compilation result is also string. concat (...), no intermediate object is generated.

Of course, multiple statements are converted into one statement. The disadvantage is that debugging is not so convenient.

Not all times can be easily converted to concatenation, for example, in the case of if, while, and other statement blocks.

The purpose of StringBuilder is to avoid generating intermediate variables, but if so:
Stringbuilder. Append ("a" + str1 + "B"), an intermediate variable is generated: "a" + str1 + "B", which should be changed
Stringbuilder. Append ("a"). Append (str1). Append ("B"). The performance is better, but the readability is almost the same.

My conclusion:It can be converted into a string concatenation StringBuilder operation, which is better to use concatenation. But try to reduce + =.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.