String resident Mechanism

Source: Internet
Author: User
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)

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.