Select string and stringbuilder in C #

Source: Internet
Author: User
Select string and stringbuilder in C #
14:26:54 let me say a few words
FavoritesI want to contribute [Font: small and big]

in many cases, stringbuilder is faster and faster than string during String concatenation.

the fact is that stringbuilder is faster than string because an intermediate object is generated during String concatenation and eventually garbage is generated.
For example:
string STR = "A";
STR + = "B";
STR + = "C";
, the final result is "ABC", but the second line produces "AB", which is just an intermediate object and garbage. Using stringbuilder will avoid the generation of such intermediate objects.

what if I write this?
string STR = "A"
+ "B"
+ "C";

is this 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, when 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 case of if, while, or other statement blocks.

the purpose of stringbuilder is to avoid generating intermediate variables, but if so:
stringbuilder. append ("A" + str1 + "B") produces an intermediate variable: "A" + str1 + "B", which should be changed to
stringbuilder. append (""). append (str1 ). append ("B"), better performance, but almost readable.

my conclusion: it can be converted into a String concatenation stringbuilder operation, which is better to use concatenation. But try to reduce + =.

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.