C # Use "+" and string. format to format string connections,
Reference: http://www.liangshunet.com/ca/201303/218815742.htm
There are two commonly used connections between strings: "+" connections, string. format formatted connections, and StringBuilder connections.
1. When will I use "+" to connect?
The number of strings to be connected is less than 6. You can use + to connect
Use + connection will eventually call String. concat method. When several strings are connected at the same time, the memory is not allocated for each connection, but several characters are regarded as strings. the Concat method parameter is allocated only once, for example:
String s = s1 + s2 + s3 + s4 + s5;
It will be compiled into: string. Concat (s1, s2, s3, s4, s5 );
It is tested that when the number of strings to be connected is less than 6, the + connection is used, and the efficiency is slightly higher than that of StringBuilder.
2. When to use StringBuilder
If there are more than 6 strings to be connected, use StringBuilder.
StringBuilder allocates memory only once. If the memory for the second connection is insufficient, the size of the memory is changed. It allocates 16 bytes by default each time. If the memory is insufficient, it is extended to 32 bytes. If the memory is still insufficient, continue to multiply.
The key to using StringBuilder is to allocate the memory. If the memory is frequently extended, the efficiency is greatly reduced. Because of the memory allocation, the time overhead is relatively large.
If you can accurately estimate the memory required during program execution in advance and allocate enough memory at a time, the efficiency is greatly improved. If you cannot accurately estimate the number of memory allocations, try to reduce the number of memory allocations.
3. character format (string. format)
The string. format method is actually calling StringBuilder. The prototype is as follows:
public static string Format(IFormatProvider provider, string format, params object[] args) { if ((format == null) || (args == null)) { throw new ArgumentNullException((format == null) ? "format" : "args"); } StringBuilder builder = new StringBuilder(format.Length + (args.Length * 8)); builder.AppendFormat(provider, format, args); return builder.ToString(); }
If there is no difference in efficiency when the number of strings to be connected is small, you can choose between StringBuilder and string. format based on convenience or habits. If many strings are connected, StringBuilder is more efficient and it is not convenient to use string. format.