C # Performance Optimization--three kinds of string concatenation efficiency

Source: Internet
Author: User
Tags string format
C # Performance Optimization--three kinds of string concatenation efficiency

String stitching consists mainly of three categories: +,string.format (), Stringbuilder.append ()

1 for a small number of fixed string concatenation, such as String s= "a" + "B" + "C", the system will be optimized to s= String.Concat ("A", "B", "C") without creating more than one string.

If written as String s= "a"; s + + "B"; s+= "C"; three new strings are created.

2) String.Format Source code:
public static String Format (
IFormatProvider provider, String format, params object[] args) {
if (format = = NULL | | args = NULL)
throw new ArgumentNullException (format==null)? Format ":" args ");
StringBuilder sb = new StringBuilder (format. Length + args. Length * 8);
Sb. AppendFormat (Provider,format,args);
Return SB. ToString ();
}

Visible, it and StringBuilder have similar efficiency, than with "+" stitching way efficient, and code easy to read.

String s= String.Format ("{0}{1}{2}", "A", "B", "C");

3 StringBuilder can specify the capacity of the memory space, but may require data type conversion. When there are fewer strings, you can use String.Format () instead.

4 A small number of string operations, you can use "+" or String.Format (), a large number of string operations, such as in the loop body, you must use Stringbuilder.append ().

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.