Cainiao tour-. NET garbage collection mechanism,. net garbage collection

Source: Internet
Author: User

Cainiao tour-. NET garbage collection mechanism,. net garbage collection

. NET's garbage collection mechanism is a very powerful function. Although we seldom take the initiative to use it, it has been running silently in the background, and we still need to realize its existence and understand it, make more efficient.. NET application. Next I will share my experiences with the garbage collection mechanism (GC.

GC necessity

We know that the program will need to use the new request memory to the memory heap, and then initialize and use the requested memory. After using the new request, it will clean up the resources and release the memory, waiting for other programs to request it; there are several ways to manage memory resources:

1. manual management: C, C ++

2. Count management: COM

3. Automatic Management:. NET, JAVA, and PHP

The current advanced language basically implements automatic memory management, because manual memory management causes the following problems:

1. The developer forgets to release the requested memory, causing memory leakage. If the memory leaks too much, it may cause memory overflow and the program cannot run;

2. applications access the released memory, causing Data Reading errors.

It can be seen that manual management of the memory reliability in the heap may vary with developers, and many problems may occur in C ++ due to pointers; and prone to bugs and other messy problems, affecting system stability, so automatic memory management is necessary.

GC working principle general concept recovery time

When an application allocates a new object, the budget of the GC generation has reached the threshold, for example, the GC 0th generation is full;

The Code explicitly calls System. GC. Collect ();

In other special cases, for example, windows reports that the memory is insufficient, CLR detaches the AppDomain, and CLR shuts down. In some extreme cases, changing system parameter settings may also cause GC collection.

Application Root

  Application Root(Application root): the root is a storage location that stores references to an object on the managed heap. The root can attribute any of the following categories.

  • Reference of global and static objects
  • References to local objects in the application code library
  • References to object parameters passed into a method
  • Wait for finalize (described later) Object Reference
  • CPU registers of any referenced objects

The garbage collector divides the objects in the managed heap into three generations (generally three generations). GC can be used. maxGeneration () method to query the maximum algebra supported by the current system:

1. G0 small object (Size <85000 Byte): newly allocated object smaller than 85000 bytes

2. G1: the surviving G0 object in GC

3. G2: Large Object (Size> = 85000 Byte); G1 object surviving in GC

When an object is new, its generation is 0. After a collection, if the object is not recycled, the generation is increased to 1. If each collection survive, the maximum number of generations supported by the operating system is increased.

Because objects are divided by generation, and a single generation can be recycled separately, the entire managed heap can be recycled to improve performance. A generation-based Garbage Collector has the following features:

1. the newer the object, the shorter the survival period;

2. The older the object, the longer the survival period;

3. reclaim part of the heap, which is faster than the whole heap.

Work Process tag object

The first step in garbage collection is to mark the object: The Garbage Collector will think that all objects in the managed heap are junk, and then the Garbage Collector will check allApplication RootTraverse the objects referenced by each root and mark them as active (live). After all the root objects are checked, the labeled objects are reachable objects, unlabeled objects are reachable objects, and inaccessible objects are the targets for recycling.

Weak referenced objects are not within the scope of consideration, so they will be recycled.

Destroy objects and release memory

After filtering the objects in step 1, The unreferenced objects are recycled, that is, the inaccessible objects. After GC calls the default Finalize () of the object, release the memory.

At the same time, there are still referenced objects, that is, the generations of reachable objects become the next generation.

Compressing heap memory

After the objects are destroyed and the memory is released in step 2, the surviving objects may not be arranged in the heap. At this time, many memory fragments exist in the heap, when a program requests a continuous memory segment for a new object, memory fragments may not be reused (although not used), resulting in a waste of memory resources, therefore, the last step of garbage collection is to compress the memory: Move the surviving objects after garbage collection together, and update the references of each object to the new position of the object to ensure the correctness of object references.

Note: we can see that when compressing the heap memory, all related threads Must be paused. Because the object reference cannot be correct during compression, during garbage collection, GC will hijack all related threads. After the collection is completed, the hijacked thread will work normally, so garbage collection will inevitably affect certain performance, so use System with caution. GC. collect ().

Finalize () and Dispose ()

As mentioned above, GC calls the Finalize () of the object during object collection, so let's simply summarize Finalize () and Dispose:

1. Caller:

Finalize can only be called by GC

Dispose is displayed and called by developers. You can also use the use block to automatically call the Dispose method when the program leaves the block.

2. Call time:

Finalize is called by GC, so the call time is called during garbage collection, and the time is not certain.

Because Dispose is a display call, the call time is determined. It is called when the method is called.

3. Purpose:

The purpose here is mainly the purpose of Dispose;

First. NET has managed resources and unmanaged resources. In general, the number of unmanaged resources is limited, which is very precious. after use, we hope to release them, it is also possible to write the method for releasing unmanaged resources to the Finalize Terminator. However, due to the uncertain call time of Finalize, the release of resources is not timely, therefore, a limited number of unmanaged resources will soon be occupied. Therefore, in order to release such resources in time, we need to be able to display the called method, which is Dispose.

Finalize is mainly used to release managed resources and destroy objects for GC and release memory.

Dispose is mainly used to release managed and unmanaged resources and destroy objects and release memory.

Note: you do not have to worry about the repeated release of resources. Even if the resources are released repeatedly,. NET also takes appropriate measures to handle the issue and will not throw an exception.

The following is a standard Dispose implementation method recommended by MSDN.

Class Class: IDisposable {// identify: whether to release managed resources private bool disposed = false; // display the called method public void Dispose () {Dispose (true ); // remove the object from the linked list of the garbage collector. // when the garbage collector is working, only the managed resources are released, and the GC of the object is not executed. suppressFinalize (this);} // protected resource release method protected virtual void Dispose (bool disposing) {if (! This. disposed) {if (disposing) {// here write the method for releasing managed resources} disposed = true; // here write the method for releasing unmanaged resources }}~ Class () {// here is to prevent the display from forgetting to call Dispose () and release the unmanaged resource Dispose (false) When GC is garbage collection );}}
View Code



The convenience brought by GC is self-evident, but this can be achieved by a certain amount of system: GC will hijack all related threads during garbage collection, and there will be a certain amount of time and space overhead, therefore, pay attention to some good development habits during the development process, which may have a positive impact on GC.

1. Try not to create large new objects. large objects (> = 85000 bytes) are directly classified as G2 generation, and GC collection algorithms never compress memory of Large Object heaps (LOH, moving large objects will consume more CPU time and cause more memory fragments. You can also pool large objects or objects with long lifecycles.

2. Do not frequently add small objects with short lifecycles, which may lead to frequent garbage collection. Here we can consider using struct instead in the stack, alternatively, you can use object pooling for optimization.

3. It is not recommended to use the object pooling solution. It is heavy and error-prone, and it is not easy to design a high-performance and stable Object pool.

4. Reduce the vertical depth between objects. During GC collection, objects are traversed and marked along the root. Reducing the depth can speed up the traversal; if the relationships between classes in the system are complicated, consider whether the design scheme is reasonable.

Of course, there are still a lot of things to pay attention to. I will post a blog post and introduce it here.How to Write high-performance. NET code, The GC introduction is very detailed:

[Translate] [Directory] Write high-performance. NET code

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: 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.