Garbage collection GC:. Net Automatic Memory Management (I) Memory Allocation

Source: Internet
Author: User

Garbage collection GC:. Net Automatic Memory Management (I) Memory Allocation
Preface

GC in. Net completely solves the embarrassment of developers tracking memory usage and controlling memory release. However, you may want to understand how GC works. This series of articles will explain how memory resources are reasonably allocated and managed, and contain a very detailed description of internal algorithms. At the same time, we will also discuss the GC memory cleaning process and when to clean up, and how to force clean up.


Introduction

Implementing reasonable resource management for your applications is a difficult and tedious task. This may shift your attention from the actual problem you are solving. So, if there is an existing mechanism for developers to manage annoying memory management, will it be a matter of high interest? The answer is YES! In. Net, there is a garbage collection mechanism called GC.


Every program needs to use some computer resources, such as memory, video card, network, database, and so on. In fact, in an object-oriented environment, each type represents the resources required by the program. If you want to use these resources, you need to allocate memory to present this type. The steps for accessing these resources are as follows:

  1. Allocate memory to type resources.
  2. Initialize memory and type resources and make the resources available.
  3. Use these resources to access the instance member information (repeated as needed ).
  4. Destroy and clear Resources
  5. Release memory

This seems simple, but it is the root source of program errors. How many times have programmers forgotten to release idle memory? How many times have programmers tried to access the released memory?

These two bugs are the worst case, because they export abnormal results and the occurrence time is unpredictable. For other bugs, you can fix them directly when you see a program running error. These two bugs are the most likely to cause program resource leaks (wasting memory) and program object crashes (unstable), and will also lead to unpredictable behavior of applications at unpredictable times. Of course, there are many tools that can be used to track and monitor such bugs.

When we test 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 any resources about the types represented in memory. This means that GC does not know and will not perform Step 4: destroy and clear resources. In the. net framework, programmers write code for destroying and clearing resources in Methods Close, Dispose, and Finalize, which will be introduced in subsequent articles. However, GC can determine when to automatically call these methods.

Some types of resources do not need to be cleared. For example, the Rectangle type can be completely cleared by destroying its left, right, width, and height in the memory. On the other hand, a file-type resource or network connection-type resource requires very clear code to destroy. I will explain how to complete these tasks as appropriate. Now let's take a look at how memory is allocated and how resources are initialized.


Memory Allocation

. Net clr allocates all resources to the managed stack, which is a bit like a heap in C language, but you do not need to release resources because idle resources will be automatically released in. NET. Now there is a problem. How does the managed heap know when an object will not be used by the program? I will give a brief introduction.
Many GC algorithms are available today. Each algorithm is optimized for a specific environment to achieve the best performance. This article focuses on the GC algorithm used by. net clr. Let's start with the basic concepts.
When a thread is initialized, an unused contiguous address space will be reserved during the runtime. This address space is the hosting Heap (a simple illustration of C # Heap and Stack C # Heap (ing) VS Stack (ing )). A pointer is maintained 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 memory address at the most basic (can be understood as the first position.

The program uses the new Keyword to create a new object. In this operation, you must first determine whether the specified address space is sufficient to store new objects (whether the memory space is sufficient ). If enough, NextObjPtr (the next object pointer) points to this object in the heap, the object constructor is called, and the memory address of the object is returned.
Hosting heap (for friends who have doubts about heap and stack, refer to: simple illustration C # heap and stack ):
(NextObjPtr: Next object pointer)


In this case, NextObjPtr skips this object and points to the memory address of the next object to be saved. For example, the managed heap has three objects: A, B, and C. The next object will be placed at the address pointed to by NextObjPtr (that is, after C ).

Now let's see how the C language heap allocates memory. In the C language heap, allocate memory for an object through a Data Structure linked list. Once a large block is found, the block is split, and then the pointer In the linked list node needs to be adjusted to ensure that all data is intact (not familiar with the C language, 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 has to be split, and pointers in the linked list nodes must be modified to keep everything intact .). For managed heap in. NET, object allocation is simple. You only need to add a value to the pointer, which is very fast. It turns out that allocating an object in the managed heap is almost as fast as allocating memory in the thread stack!

So far, it seems that the hosting heap is far better than the C language heap in terms of speed and simplicity. However, to make the managed heap possess these advantages requires a large premise: the address space and storage space are infinitely large. Of course, this is not practical, but the managed heap must use some mechanisms to make this so-called assumption true. This mechanism is garbage collection GC. Let's see how it works.

When a program creates a new object using the new operator, it may not have enough address space to store it. To check whether the address space is sufficient, the managed heap will try to place the object in the NextObjPtr position. If NextObjPtr moves beyond the address space boundary, it indicates that the heap is full, and GC recycles the garbage.

In fact, GC will collect garbage when The 0th generation (the generation in GC will be introduced later) is full. In short, the generation in GC is a mechanism implemented by GC to improve program performance. In principle, the newly created object belongs to the younger generation of GC, and the objects created earlier in the application lifecycle belong to the older generation. Dividing objects into different generations allows the GC to know the specific generation for garbage collection, rather than recycling the entire managed heap.


Summary

This article aims to give you a preliminary understanding of garbage collection GC and memory allocation. It is important to know about memory allocation for a programmer if you want to write high-performance code. Although we don't have to allocate memory manually like using the C language, programmers who are ignorant of memory allocation will be a little bit despised (just a little bit, okay, no offense, please do not misunderstand ). The next article will continue to introduce the automatic memory management of garbage collection GC: Memory algorithm.


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

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.