Comparison of string splicing function between string and StringBuilder in NET

  • 2021-11-01 02:52:20
  • OfStack

string and StringBuilder have different execution efficiency in string splicing, Because one trick is used in the StringBuilder class: It applied for twice the memory space for strings, When the Append method is called to splice a string, It will first check whether the remaining space can put down the string to be spliced. If it can be put down, the string to be spliced Copy will be put into the remaining space. If it cannot be put down, it will apply for twice the length of the spliced string and put the current string Copy into the new space (except for twice the space, this is not much different from the splicing of string). Therefore, StringBuilder can improve the efficiency of string splicing because it reduces the number of requests for memory allocation and the number of strings Copy. So here are the following four situations:

1. The original long string is spliced with a short string.

In fact, this is the most consistent with StringBuilder's intention of applying for extra space and can achieve the best results. The specific situation is as follows, Suppose an StringBuilder holds an initial string length of 1000, So when you instantiate this StringBuilder, Will apply for 2000 space, Then, splice strings of length 20 at a time, The string with a length of 20 will be directly placed in the remaining 1000 spaces in sequence until it is full, during which there are 50 splicing operations. At this time, if another string with a length of 20 is spliced, because there is not enough space, StringBuilder will apply for 2000*2=4000 space, and then the original spliced string with a length of 2000 Copy will continue to splice the new string with a length of 20. This last step is almost as efficient as the string operation, mainly because the first 50 splices can reduce the memory creation by 50 times and the efficiency loss of Copy from all strings to new strings. If string is spliced, one new memory will be allocated each time in the first 50 splicing operations, and all existing strings will be Copy into the new memory.

2. The original long string is spliced into a long string.

At the beginning, this situation will run out of space quickly, which does not reflect the advantages of StringBuilder in string splicing, but with the increase of splicing times, it will be converted to the first situation.

3. The original short string is spliced with a short string.

4. The original short string is spliced into a long string.

In fact, the latter three situations should be evaluated according to the actual situation, and eventually they should all change to Situation 1. So our focus is mainly on the length gap between the spliced string and the existing string, and how many times of temporary memory allocation can be reduced to achieve the purpose of improving the efficiency of string splicing.


Related articles: