C # 's CLR Memory string Chang (String)
Submission: shichen2014 font: [Increase decrease] Type: Reprint time: 2014-08-04 I want to comment
This article mainly introduces C # 's CLR Memory string Chang (String), for learning and Understanding C # Memory principle is very helpful, the need for friends can refer to the following
The string in C # is more than a special class, which says reference types, but does not exist in the heap, and string Str=new string ("HelloWorld") such as the reload also said no.
Let's look at a method first:
?
12345678 |
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 is played:
?
1234567891011121314 |
.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 instructions in the newobj (so we don't think it was in the heap), only a special ldstr (load string) directive, which constructs a string object with a literal constant string (a string constant pool) obtained from the metadata. This proves that the CLR has said that it constructs a string in a special way.
Let's look at a simple example:
?
1234567891011 |
class Program
{
static void Main(
string
[] args)
{
String s =
"HelloWorld"
;
s =
"HelloC#"
;
s =
"HelloJava"
;
String s1=
"HelloC#"
;
Console.WriteLine(s);
}
}
|
In contrast to this example, let's see how the Memory map goes:
First the CLR internal mechanism will have "prologue" code to open up memory space before running this method, and S and S1 say this time to create.
We created a string object of S, assigned a value of HelloWorld, put s into the stack, and then the internal mechanism went to the string constant pool to find the HelloWorld copy, found that no found will create a, and then to save this HelloWorld in the string constant pool address ( LINE1). Then we assign the S object to helloc#, because the same object, do not operate in the stack, go to the string constant pool to find, not found then create, and then modify the address stored by S (Line 2), Hellojava the same operation. Then create a S1 string object, put the S1 into the stack, for the S1 assignment helloc#, this time will go to the character constant pool to find, found to save this reference.
C # 's CLR Memory string Chang (String)