String is a special class. It indicates the reference type, but it does not exist in the heap. In addition, reinstallation like string STR = new string ("helloworld") also means no.
Let's first look at a method.
class Program { static void Main(string[] args) { String s = "HelloWorld"; Console.WriteLine(s); } }
Then we use the ildasm.exe tool to generate the Il language to see how it works:
.method private hidebysig static void Main(string[] args) cil managed{ .entrypoint // Code size 15 (0xf) .maxstack 1 .locals init ([0] string s) IL_0000: nop IL_0001: ldstr "HelloWorld" IL_0006: stloc.0 IL_0007: ldloc.0 IL_0008: call void [mscorlib]System.Console::WriteLine(string) IL_000d: nop IL_000e: ret} // end of method Program::Main
We didn't see the newobj command in it (so we don't think it's in the heap). There is only one special ldstr (load string) command, it acquires a text constant string (String constant pool) from metadata to construct a String object. This proves that CLR constructs strings in a special way.
Let's take a simple example:
class Program { static void Main(string[] args) { String s = "HelloWorld"; s = "HelloC#"; s = "HelloJava"; String s1= "HelloC#"; Console.WriteLine(s); } }
Let's see how the memory diagram goes:
First, the CLR internal mechanism will have the "prologue" code to open up the memory space before running this method, and S and S1 will say it was created at this time.
We created a String object of S, assigned a value of helloworld, and inserted s into the stack. Then, the internal mechanism went to the String constant pool to find the helloworld copy. If it was not found, a new one would be created, the address (line1) of helloworld In the String constant pool will be saved ). Then we assign the value of S object to helloc #. Because the same object is not operated in the stack, it is found in the String constant pool. If it is not found, it is created, then modify the address (line 2) stored by S, and perform the same operations in hellojava. Create a String object of S1, press S1 into the stack, and assign helloc # to S1. At this time, locate it in the character constant pool, and store the reference.