In either language or platform, strings are the most commonly used objects.
The. NET and C # languages make strings quite easy to use on the surface, but only after a deep understanding of the string's resident form in CLR can we use string objects more reasonably and efficiently.
1. Resident form of string
First look at a sample
Static Void Main ( String [] ARGs)
{
// . NET Framework stores the strings of an application in a hashtable.
// Key is the value. value is the heap address.
String Str1 = " Hello " ; // Apply for a heap memory and place the address in the element where the key of stringhashtable is hello.
String Str2 = " Hello " ; // Because the previous statement has created an element with the key as hello, newobj is not used to apply for a new heap memory.
String Str3 = " H " + " E " + " L " + " L " + " O " ; // It is already the same as string str3 = "hello" when compiled into msil.
String Str4 = New String ( New Char [] {'H','E','L','L','O'} ); // Display it by yourself for new
String Str5 = " Hello2 " ; // Apply for a heap memory key of hello2
Console. writeline ( Object . Referenceequals (str1, str2). tostring ()); // True references the same heap memory
Console. writeline ( Object . Referenceequals (str1, str3). tostring ()); // True also references the same heap memory.
Console. writeline ( Object . Referenceequals (str1, str4). tostring ()); // False references different heap memory
Str2 = " Hello2 " ; // Each time a String object is assigned a value, str5 is first retrieved from stringhashcode to see if duplicate keys exist.
Console. writeline ( Object . Referenceequals (str1, str2). tostring ()); // False str2 and str1 do not reference the same heap
Console. writeline ( Object . Referenceequals (str2, str5). tostring ()); // True becomes the same heap memory referenced by str5
Str1 = Console. Readline ();
Str2 = Console. Readline ();
Console. writeline ( Object . Referenceequals (str1, str2). tostring ());
Console. writeline ( Object . Referenceequals (str1, String . Empty). tostring ());
Console. Readline ();
}
At the beginning, str1, str2, and str3 are actually the same string STR = "hello" after being translated into msil ";
Then the applicationProgramThere will be a string pool, which should be a hashtable that stores all the strings, followed by str2 = "hello2", so that str2 and str5 point to the same memory.
Finally, I tried to test whether the string pool mechanism is enabled at runtime. I found that the string pool only optimizes the size of the application when the application is started, the memory usage is optimized, but this mechanism is not available during runtime. Every time a string is assigned a value, a new space is allocated in the heap memory.