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