SoFunction
Updated on 2025-03-07

Detailed explanation of string memory residency mechanism


// Memory residency mechanism of string
        public static void Test()
        {
//When there are multiple string variables that contain the same string actual value,
//CLR may not allocate memory for them repeatedly, but instead let them all point to the same string object instance.

            String s1 = "Hello";
            String s2 = "Hello";
bool same = (object)s1 == (object)s2;//Compare whether s1 and s2 are the same reference
(same);                                                                                                                             �

            /*
* We know that there are many special things about the String class, one of which is that it is "immutable".
* This shows that when we operate on a String object every time (for example, using Trim, Replace, etc.),
* It is not really a change to the instance of this String object, but a new String object instance is returned as the result of the operation execution.
* Once an instance of the String object is generated, it will not be changed until death!
             */

/*About the residency pool: It maintains what literal strings, but does not maintain the following type*/
            StringBuilder sb = new StringBuilder();
            ("Hel").Append("lo");
            String s3 = "Hello";
String s4 = (); //Although the value is the same, it is not the same reference

            bool same2 = ((object)s4 == (object)s3);
            (same2);

/*Let the programmer force CLR to check the residency pool; see if there is the same string*/

            StringBuilder sb2 = new StringBuilder();
            ("He").Append("llo");
            string s5 = "Hello";
            string s6 = (());

            bool same3 = (object)s5 == (object)s6;
            (same3);
        }