Garbage collection GC:. NET automatic memory management on (a) memory allocation

Source: Internet
Author: User

Garbage collection GC:. NET automatic memory management on (a) memory allocation
Objective

. NET, the GC completely solves the embarrassment that the developer keeps track of memory usage and controls the release of memory. However, you may want to understand how the GC works. This series of articles will explain how memory resources are properly distributed and managed, and contain very detailed intrinsic algorithm descriptions. At the same time, we will discuss the GC's memory cleanup process and what to clean up and how to force cleanup.


Introduction

Implementing reasonable resource management for your application is a difficult and tedious task. This may divert your attention from the actual problem you are currently solving. So, if there is an existing mechanism for developers to manage the offensive memory management, will it be a pleasant thing? The answer is yes!. In. NET, there is a garbage collection mechanism called a GC.


Each program needs to use some computer resources, such as memory, graphics card, network, database and so on. In fact, in an object-oriented environment, each of these types represents the resources that the program needs to use. If you want to use these resources, you need to allocate memory to render this type. Here are the steps to access these resources:

    1. Allocates memory to a type resource.
    2. Initialize memory and type resources and make resources available.
    3. Use these resources to access type instance member information (repeat on demand).
    4. Destroying and cleaning up resources
    5. Freeing memory

This may seem simple, but it is a fundamental source of procedural errors. How many times have programmers forgotten to release idle memory? How many times has the programmer tried to access the freed memory?

These two kinds of bugs are the worst, because they lead to unpredictable results and the time of occurrence. For other bugs, just fix it when you see the program running out of error. These two bugs are most likely to cause program resource leaks (wasted memory) and program objects to crash (unstable), and also to cause unpredictable behavior in the application at unpredictable times. Of course, there are many tools available to track and monitor this bug.

When we test the GC, you should know that it completely solves the problem of developers tracking memory usage and determining when to release memory. However, garbage collection GC does not know anything about the types of resources represented in memory. This means that the GC does not know and is not going to perform step fourth: Destroy and clean up resources. In the. NET Framework, programmers write code about destroying cleanup resources in method Close,dispose,finalize, which is described in subsequent articles. However, the GC can determine what to call these methods automatically.

There are some types of resources that do not need cleanup. For example, the rectangle type can be completely cleaned up by destroying its left,right,width and height in memory. On the other hand, a file type resource or network connection type resource requires very explicit cleanup code to destroy. I will explain how to accomplish these tasks properly. Now, let's look at how memory is allocated and how the resources are initialized.


Memory allocation

The. NET CLR allocates all resources to the managed heap, which is a bit like the heap in C but you don't have to release resources because idle resources are automatically freed in. NET. Now there is a problem, how does the managed heap know when an object will no longer be used by the program? I'll give you a brief introduction.
There are a lot of GC algorithms nowadays. Each of these algorithms is tuned for a particular environment to achieve the best performance. This article focuses on the GC algorithm used by the. NET CLR. Let's start with the basic concepts.
When a thread is initialized, the runtime will reserve an unused contiguous address space. This address space is the managed heap.(In-depth illustration of C # heap and Stack C # heap (ing) VS stack (ing))。 While maintaining a pointer in the heap, we call it the next object pointer. This pointer tells us where the next program object will be allocated to the heap. At the beginning of the program, this pointer is set to the most basic memory address (which can be understood as the first position).

The program creates a new object by using the New keyword. This operation first needs to determine if the intended address space is sufficient to store the new object (enough memory space). If enough, Nextobjptr (the next object pointer) points to this object in the heap, the object constructor is called, and finally the object memory address is returned.
managed heap (for a friend of heap and stack confusion, refer to the C # heap and stack):
(nextobjptr: Next object pointer)


At this point, Nextobjptr skips this object and points to the memory address of the next object that will be deposited. For example, there are three objects in the managed heap: A,b,c. The next object will be placed at the address pointed to by Nextobjptr (immediately after C).

Now let's take a look at the C-language heap. Allocation of memory. In the C-language heap, allocating memory for an object needs to pass through a list of data structures. Once a larger block is found, the split block is made, and the pointer in the linked list node needs to be modified to ensure that all data is intact (C language is not ripe, original: In a c-runtime heap, allocating memory for an object requires Walking though a linked list of data structures. Once a large enough block is found, that block have to being split, and pointers in the linked list nodes must are modified to Keep everything intact. ). For managed heaps in. NET, object allocation is simple, and it is very fast to add a value to the pointer. It turns out that allocating an object in the managed heap is almost as fast as allocating memory online Cheng!
   

Up to now, it sounds as if the managed heap is far superior to the C language heap in speed and simplicity of implementation. However, having these benefits for the managed heap requires a major premise: address space and storage space are infinitely large. Of course, this is somewhat unrealistic, but the managed heap must use some mechanism to make this so-called hypothesis come true. This mechanism is garbage collection GC. Let's see how it works.

When a program uses the new operator to create an object, there may not be enough address space to place it. In order to detect if the address space is sufficient, the managed heap will try to place the object in the Nextobjptr position, and if the nextobjptr is moved beyond the address space boundary, it indicates that the heap is full and the GC is garbage collected.

In fact, the GC will be garbage collected when the No. 0 generation (the generation in which the next article describes the GC) is full. In short, the generation in GC is a mechanism implemented by GC to improve program performance. The principle is that the newly created object belongs to the younger generation of GC, and the objects created earlier in the application life cycle are older generations. Dividing objects into different generations allows the GC to know the specific generation to be garbage collected, rather than reclaiming the entire managed heap.


Summarize

This article is intended to give you a preliminary idea of garbage collection GC and memory allocation, and it's important to understand that memory allocation is essential for a programmer if you want to write high-performance code. While we don't have to allocate memory as much as we do with C, a programmer who is clueless about memory allocation is more or less despised (just a little bit, OK, no offense, please don't misunderstand). The next article will continue to describe the automatic memory management of garbage collection GC: Memory algorithm.


Translation: Http://msdn.microsoft.com/en-us/magazine/bb985010.aspx

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.