C Special string Type Detailed Explanation

  • 2021-12-04 10:58:36
  • OfStack

1. Preface

string is a reference type, does everyone know that? However, in the process of using it, it is found that it still has some characteristics of value types. Why is this?

The reason. Net considers that if a large number of string objects are operated, when a large number of reference objects are operated, the performance is definitely not as refreshing as value types. To improve this performance, Net provides a special solution: string resident pool!

2. Text

Let's look at one piece of code first:


      string str1 = "aa";
      string str2 = "a" + "a";
      Console.WriteLine(ReferenceEquals(str1, str2)); //print : true

This str1 and str2 memory point to the address is actually 1 mode 1 sample!

The reason is that. Net maintains an Hash table inside CLR (in fact, it is the string resident pool mentioned above), key is the string content, and the value is the address of the managed heap pointed to; When initialization creates a new string,. Net will search for the same value in this Hash table. If key is the same, the address value of the existing string will be assigned to the newly created string, and if it does not exist, the address will be reassigned, which is why the memory of the above code is true.

Let's look at another piece of code:


     string str3 = "ab";
     string str4 = "a";
     str4 += "b";
     Console.WriteLine(ReferenceEquals(str3, str4));//print  : false

The reason why false appears, please pay attention to the keyword "initialization creation" in the previous column. When the string is dynamically created,. Net will not search for whether it has been created in the Hash table, but will be created directly;

If we want to optimize the above code 1 and have higher performance (xian) (de) (dan) (teng), we can manually add this string to the string resident pool for comparison


       string str3 = "ab";
     string str4 = "a";
     str4 += "b";
     str4 = string.Intern(str4);//Intern: It will search the string resident pool and return the corresponding address if it is found 
     Console.WriteLine(ReferenceEquals(str3, str4));//print  : true

3. Summary

Finally, the conclusion of string is as follows:

1. string is not created with the newobj directive in clr, but with the ldstr directive! Moreover, string has the characteristics of value type, but it is a reference type in memory and exists on the managed heap;

2. string is modified by sealed, so it cannot be integrated by subclasses;

3. When creating the same content, string points to the same address, and every operation of string will generate a new address (constancy of string);

4. If you use StringBuilder for a large number of splices, it is dynamic, unlike string, which is constant, but it costs a lot to create StringBuilder, so it may be better to use string for small splices!


Related articles: