String S = "hello ";
Console. writeline (object. referenceequals ("hello", s ));
You can guess whether it is true or false. Many people may guess false. Do you think there are two "hello" objects? But it should actually be true. Why? The following explains:
In fact, during CLR initialization, it will create an internal hash with the key as a string and the value as a reference to the string object in the managed heap. The table is empty at the beginning. When the JIT compiler compiles a method, it searches for each text constant string in the hash. Now let's take a look at the aboveCode, JIT first searches for the first "hello" in the hash list. If no "hello" is found, it constructs a New String object in the managed heap, then, add the "hello" string and reference pointing to the object to the hashed list. Then, JIT searches for "hello" for the second time in the hash list. If "hello" is found this time, no other operations will be performed (other string objects are not constructed ).
When the code is executed, it will find a "hello" string reference in the first line. Therefore, CLR finds "hello" in its internal hash and finds the string object we created previously (see the red letter above) is saved in variable S ., When the second line of code is executed, CLR finds "hello" in the hash and finds it. Then, only the reference of the same string object (see the red letter above) is passed to the first parameter of object. referenceequals. Of course, true is returned.
When a string reference method is compiled by JIT, allSource codeThe text constant string in is always added to the CLR hash. What about Dynamically creating strings? What will happen?
I want to eat. After dinner, I will come back and continue writing.
NOTE: Refer to. NET Framework in this article.ProgramDesign (revision)