C# efficiency comparison of multiple strings concatenation

Lionsure 2020-07-20 Original by the website

C# provides three methods of string concatenation, which are directly using +, character format(string.format), and StringBuilder. How efficient and when should they be used? The following analysis respectively.

 

1. When to use + to connect

If there are less than 6 strings to be connected, you can use + to connect.

Using the + will eventually call the String.Concat method. When connecting several strings at the same time, memory is not allocated once for each connection, but several characters are used as the arguments of the String.Concat method, and the memory is allocated only once. Such as:

string s = s1 + s2 + s3 + s4 + s5;

Will eventually be compiled into: string.Concat(s1, s2, s3, s4, s5);

After testing, when the number of strings to be connected is less than 6, using +, the efficiency is slightly higher than StringBuilder.

 

2. When to use StringBuilder

If there are more than 6 strings to be connected, it is more appropriate to use StringBuilder.

StringBuilder allocates memory only once. If the memory is insufficient for the second connection, the memory size is modified; it allocates 16 bytes by default each time, if the memory is insufficient, it expands to 32 bytes, if it is still insufficient, continue to expand exponentially.

The key to using StringBuilder is to allocate memory well. If memory is expanded frequently, the efficiency will be greatly reduced, because the time overhead for allocating memory is relatively large. If the memory required during program execution can be accurately estimated in advance, sufficient memory can be allocated at one time, and efficiency will be greatly improved. If it cannot be accurately estimated, try to reduce the number of memory allocations.

The use of StringBuilder is as follows(for example, to connect a SQL statement):

StringBuilder sb = new StringBuilder();
       sb.Append("Select * From Products Where userId='");
       sb.Append(userId);
       sb.Append("' And AddDate >= '");
       sb.Append(dt);
       sb.Append("'");

 

3. Character format(string.format)

string.format method, in fact, finally calls 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 there are fewer strings to be connected, you can freely choose between StringBuilder and string.format according to convenience or habit. If there are many strings to be connected, StringBuilder is naturally more efficient, and it is not convenient to use string.format.

 

The usage of string.format is as follows:

string userId = "yooble";
       string dt = "2020-07-20";
       string str = string.format("Select * From Products Where userId='{0}' And AddDate >= '{2}'", userId, dt);