Binning and packing memory allocation and Data Copying
Demo1:
Int I = 100;
Object o = I;
I = 200;
In this instance, the program executes a packing operation. CLR allocates a memory area for the object o on the GC stack, and copies 100 of the data in I to the o memory block. Note: Here is a copy, not a move, so there is still a block of memory on the Stack that stores I. When I = 200 is executed, the I value on the Stack is changed, while the o value on the GC Stack is not changed.
This instance may be easy to understand. Let's look at the following instance.
Demo2:
Int I = 100;
Object o = I;
Object a = o;
A = 300;
Here, the program executes two packing operations. First time: object o = I; second time: a = 300;
The first two statements of this instance are easy to understand. Object a = o; at this time, CLR does not allocate a memory block for a (because the object is of the reference type ), CLR returns a pointer to the memory that a points to (both o and a are actually just pointers ). When a = 300; is executed, this is the second packing. As mentioned earlier, packing is a copy of data. Therefore, the CLR allocates a memory block, put the value of 300 in the memory block, and change the pointer of a to the memory of 300. It can be seen that o and a point to different memory blocks. GC. ReferenceEquals (o, a); Return false;
It may be easy to understand here. Let's look at the following example.
Demo3:
Public class Class1
{
Public int I;
}
Static void Main ()
{
Class1 class1 = new Class1 ();
Class1. I = 100;
Class2 class2 = class1;
Class2. I = 200;
Class2 = null;
}
In this instance, the program does not perform any packing operations. Because I in the Class1 type is a value type, it should be noted that not all value types are allocated on the Stack. Here, the value type is a value type in the reference type. It is allocated to the GC stack. in the program, class1 and class2 point to the same memory zone, and all their operations are performed on the data in this memory zone. So the final I value is changed to 200 by class2.