C # understanding of stack, heap, value type, and reference type (excerpt)

Source: Internet
Author: User

1. What is GC?
The full name of GC is garbage collection. The Chinese name is garbage collection, which is a function of Memory Management in. net. The garbage collector tracks and recycles the objects allocated in the managed memory, and periodically recycles the memory allocated to objects not effectively referenced. GC is automatically executed when the available memory cannot meet the memory request. During garbage collection, the garbage collector first searches for hosted objects in the memory, then searches for referenced objects from the managed code and marks them as valid, then release the objects not marked as valid and reclaim the memory. Finally, sort out the memory to move the valid objects together. This is the four steps of GC.
As can be seen from the above, GC has a great impact on performance, so it is better to avoid this problem as little as possible.
To reduce performance impact ,.. net GC supports object aging, or the concept of generational generation. Generation refers to the measurement unit of the object in the memory relative to the current period. The object algebra or the current period indicates the generation of the object. Currently, the. net Garbage Collector supports three generations. For each GC, objects that are not recycled are automatically upgraded to the next generation. Recently created objects belong to a newer generation, which is lower than the algebra of objects created earlier in the application lifecycle. Objects in the most modern era are in the middle of the zero generation. During each GC, the zero-generation objects are recycled first. The objects with higher algebra are recycled only when the objects with lower algebra still cannot meet the requirements.

2. Read the article and see a metaphor for the difference between stack and stack. Very good image:
Using Stacks is like eating at a restaurant, just ordering food (sending an application), paying for it, and eating (using it). If you are full, you can leave, without having to worry about the preparation work, such as cutting and washing dishes, as well as the cleaning and tail work such as washing dishes and flushing pots, his advantage is fast, but his degree of freedom is small.
Using heap is like making your favorite dishes. It is troublesome, but it suits your taste and has a high degree of freedom.

3. GC, stack, and heap
From the above concepts of stack and stack, we can see that there is no garbage collection problem in the stack. You only need to directly press the stack, and the stack is facing a very complicated garbage collection problem. GC fully operates on the heap, and the judgment on whether the objects in the heap are valid is implemented by traversing the stack. This involves the reference counting concept. reference counting is the statistics on the number of times objects in the heap are referenced. When the reference counting of an object is zero, this object can be recycled. During GC, the garbage collector traverses the stack. When a heap address is found, it adds 1 to the reference count of the object on the heap address, then, all objects with zero reference count in the heap are destroyed, the memory is reclaimed, and fragments in the heap are sorted out.

4. Class instantiation steps
Class is the most common and the most commonly used reference type. We know that instantiating a class uses a common statement:
ClassA ca = new ClassA ();
In this short sentence, what has the computer done?
In fact, the computer has done so many things in this process:
First, an empty reference pointer is generated during ClassA ca and pushed into the stack:
Then, when new ClassA () is created, a new instance of ClassA is generated and placed in the heap:
In the value = step, point the reference pointer of ca to the newly generated instance:
This completes the operation of the entire statement.

5. Special Case: string type and heap
As you know, the string type is a reference type. However, it has some value-type features. For example, if one of the two string variables points to the same string is changed, the other string variable is not affected. This is because:
(1) CLR uses a technology called string resident.
String str1 = "abc ";
String str2 = "abc ";
During CLR initialization, an internal hash is created. The key is a string and the value is a reference to the string in the managed heap. At the beginning, the hash is empty. During JIT compiler compilation, every text constant string is searched in the hash. The "abc" string is first searched because it is not found, the compiler constructs a New String object reference pointing to "abc" in the managed heap, and then adds the "abc" String and reference pointing to this object to the hash list.
Next, find the second "abc" in the hash list. This time, the compiler does not perform any operations because the string is found, and no other text constant strings exist in the code, after the compiler task is completed, the Code starts to be executed. During execution, the CLR finds that the first statement requires a "abc" string reference. Therefore, the CLR searches for "abc" in the internal hash and finds it, in this way, the reference to the previously created String object is saved in the variable s1. When the second statement is executed, the CLR will find "abc" in the hash again ", it will still be found, and the reference pointing to the same String object will be saved in variable s2, so s1 and s2 point to the same reference, so System. object. equals (s1, s2) returns true.
(2) When the overload operator "=" is used to assign a value to the string object, the string object is of the reference type and is retained on the stack instead of the stack. therefore, when a string is assigned to another string, two references to the same string in memory are obtained. for example, if you modify one of the strings, A New string object will be created (note that this process occurs in "="), and the other string is not changed.

6. the C # value type is allocated to the stack.
Value types: bool, byte, char, decimal, double, enum, float, int, long, sbyte, short, struct, uint, ulong, ushort.
7. The reference type in C # is allocated to the heap. In the stack, create a reference pointing to the heap and return it to the declared variable.
Reference Type: class, delegate, interface, object, string

Note: 1. Although the value type array is allocated to the stack, the array element is still of the value type and is not boxed.
2. The value type members of the referenced object are also allocated to the stack along with the object. They are also value types and are not boxed.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.