Illustration of the essential differences between. NET Stack and Heap, illustration of. netstackheap
Now I feel more and more right. to improve the programming level, first from. NET Stack and Heap, the computer memory can be divided into code block memory, stack memory and heap memory. The code block memory is the place where the machine code of the program is stored when the program is loaded. Stack stores local variables in the function. Heap stores global variables and class object instances. If only one object is declared, the address space is allocated for it in the stack memory. If it is instantiated, the space is allocated in the heap memory.
1 Stack VS Heap
Since the computer's memory allocation process is abstract, the following is a simple program snippet to illustrate the impact of harmonious steps on Stack and Heap memory:
The following StackvsHeap class has a Person class and a Fun1 method. When the Fun1 method is called, the first line of code is executed, that is
int i=3;
In. NET, except for string, object, class, delegate, and interface, other types are numerical types, which are generally (not all) stored in the Stack memory. Int I = 3 is a non-static variable in the function, and the numeric type is not a reference type. In this case, an area is allocated in the Stack memory to store the name and value of the variable.
When the second statement is executed, that is
int j=i;
. NET will also allocate a region in the Stack memory to store the name and value of the variable. And the address block is above I = 3 (LIFO ).
When the third sentence, that is
Person p = new Person();
We can take two steps:
1) allocate a Person-type p reference variable on the Stack (pointing to the address on Heap );
2) allocate a space on Heap to store the instance data of the Person class;
The specific process is shown in:
2. Value Type and reference type
After understanding the above process, it is easier to understand the value type and reference type variables:
First look at the figure below:
Since int j = I is an int type and is a value type variable, j = 3 is a copy of I = 3. Therefore, modifying I will not modify j, neither will I be modified when j is modified;
In Person p2 = p, Person is a class and a reference type. Therefore, p2 and p point to the same heap address block. Therefore, modifying the p2 value affects the p value.