We know that C # is a virtual machine language. In C #, the compiler first sets C #CodeCompile the code into Il and runProgramWhen CLR (Common Language Runtime,By calling JIT (Just-in-time Compiler,Real-time compiler) to dynamically compile the Il generation into executable machine code. There is a very important concept in CLR: clr gc (Garbage Collector, Garbage Collector ),GC automatically allocates and releases memory management for our applicationsTherefore, in. NET applications, memory leakage, pointer suspension, and Uninitialized pointers are rarely found. This is also the biggest difference between the virtual machine language like C # and local languages such as C/C ++.
However, GC is not omnipotent. We also need to clean up and manageUnmanaged objects, They are usuallyThe object that wraps the operating system resources, for example,File handle, window handle, or network connection.
This is because external resources are beyond the capability of running (virtual machines), and these unmanaged resources are controlled by the operating system.
If the event handler function and delegate are used to establish a link between the object, it may also cause the objects to reside in the memory for a longer period of time than you expected. At the same time, queries like the ones in the LINQ system that are actually executed only in the request results will also cause the same problem (Because the query will encapsulate the local variables to be bound using the closure, and the bound object will be released only when the query results leave the scope.). We can see that developing applications in the hosting environment and understanding the CLR memory management mechanism are very beneficial for us to write more efficient and robust code.
Reading directory:
1. Mark and compact)
2. Clear unmanaged Resources
2.1 implement Terminator
2.2 implement the idisposable Interface
3. Section
Further reading and reference
1. Mark and compress Algorithm (Mark and compact)
GC uses "Mark and compress "(Mark and compact) The algorithm analyzes the relationship between running objects and clears some of the objects that cannot be reached from the memory. GC starts from the root object of the application program and determines whether an object is reachable by traversing the object tree structure, rather than tracking the reference of each object as COM.
We can assume that there is an entityset, which is a collection of objects read from the database. Each entity object may contain references to other entity objects, and may also contain connections to other entity objects. Similar to the entity set in a relational database, these links and references may also be cyclical. Each entityset contains a series of complex references between object graphs. But we don't need to worry about this. GC will do this job well for us. GC simplifies this operation by determining whether an object (graph) is spam-the reference of this object will not be retained when the application does not need an object. GC judges objects that are not referenced by any objects or indirectly as spam.
GC runs in its special thread,GC not only automatically clears unused memory for the program, but also compresses the hosted heap. Therefore, the space in the memory is a piece of continuous memory.
The following figure shows the status of a managed heap before and after a garbage collection:
We can see that GC not only clears memory that is not in use, but also moves other objects in the memory to compress the memory in use and increase the available memory space.
2. Clear unmanaged Resources
Now we know that the memory management on the hosting stack is the responsibility of GC. However, the memory management of unmanaged resources is the responsibility of our developers .. NET provides two mechanisms for controlling the lifecycle of unmanaged resources: finalizer and idisposable.
2.1 (Terminator) finalizer
By callingFinalize ()MethodNotify GC to clear the memory used by the object while clearing its unmanaged resources.The Terminator is a defensive method that allows your objects to be released regardless of the way they are used. The Terminator is called by GC. The call will take place at a certain time after the object becomes garbage (we cannot accurately know the specific time of its occurrence, only knowing that this will happen after the object is reachable ). This is quite different from C ++. Experienced C ++ developers often allocate key resources in constructors and release them in destructor.
2.1.1 use of Terminator
In C #, The Terminator will be executed sooner or later, but the execution time is unpredictable (or not ). The Terminator can only ensure that the unmanaged resources allocated to a given type of object will be released, but its execution time is indeed unpredictable. Therefore:We 'd better avoid using the terminator in our code, and try to make the code logic use the Terminator as little as possible..
Depending on the terminator also causes performance loss. Objects that need to execute the terminator bring additional performance overhead to GC. When GC finds that an object is spam and the object needs to execute the Terminator, it cannot be removed directly from the memory: first, GC will call the Terminator, the Terminator is not executed on the thread that executes garbage collection. GC puts all the objects that need to execute the terminator in a dedicated queue, and then asks another thread to execute the terminator of these objects.UseFinalizeThe method to recycle the memory used by the object requires at least two garbage collections. All we know:Use the terminator to release unmanaged resources. Resource objects will not only stay in the memory for a longer time, But GC also requires additional threads to run..
2.1.2 concept of "Generation" (generation) in GC
To optimize the execution of. Net GC, the "Generation "(Generation. This concept allows GC to quickly find objects that are more likely to be spam.
After the last garbage collection, the newly created object belongs to The 0th generation object. If the object remains alive after the last garbage collection, it will become a 1st-generation object. If two or more garbage collection objects are not destroyed, the object becomes a 2nd-generation object.
This generational approach is used to separate local variables from objects that have been used throughout the application lifecycle. Most of the 0th s are local variables. The member variables and global variables will become 1st generation objects until they become 2nd generation objects. GC optimizes the execution process by reducing the number of checks for the 1st and 2nd generations. Of the GC of about 10 cycles, only one will check the 0th and 1st generations of objects at the same time; of the GC of about 100 cycles, all objects will be checked at the same time. All, an object that requires a terminator may stay at 9 GC cycles more than a common object. For 2nd-generation objects, it even takes more than 100 GC cycles to have the opportunity to be destroyed.
2.2 idisposable Interface
Compared with the TerminatorIdisposable InterfaceThe ability to release unmanaged resources in a timely manner in a way that has less impact. Using the idisposable interface to release unmanaged resources can avoid the performance impact of the terminator execution on GC. Implement the idisposable Interface DisposeMethod should release all its resources. It should also release all resources of its base type by calling its parent typeDisposeMethod.
Section:
GC automatically allocates and releases memory management for our applicationsTherefore, in. NET applications, memory leakage, pointer suspension, and Uninitialized pointers are rarely found. Unmanaged resources must be released using the Terminator. Even if the terminator has a great impact on the performance of the programThe Terminator must be provided.This is to prevent resource leakage. However, the use of the idisposable interface to release unmanaged resources can avoid the impact of the execution of the Terminator on GC performance.
Reference & further reading
Msdn: Automatic Memory Management
Msdn: Managed execution process
Msdn: Clear unmanaged Resources
Msdn: In-depth discussion on idisposable
Cai xueyun: Automatic Memory Management of. net
Wikipedia: runtime in public languages
Objective C #