.net garbage collection (GC) principle
As part of the advanced content of .NET, the garbage collector (GC for short) is something you must understand. In line with the principle of "easy to understand", this article will explain the working principle of the garbage collector in the CLR.
Basic knowledge
Managed Heap
Let’s first look at MSDN’s explanation: When initializing a new process, the runtime will reserve a continuous address space area for the process. This reserved address space is called the managed heap.
"A managed heap is also a heap", why do you say this? I say this because I hope everyone will not be confused by "terminology". The premise of this knowledge point is "the difference between value types and reference types." It is assumed here that the reader already knows the important concept of "value types are stored on the stack, and reference types are stored on the heap. (References of reference types are stored on the stack)". So, according to this theory, the CLR requires that all resources, except value types, be allocated from the managed heap.
The managed heap maintains a pointer, here named NextObjPtr, which points to the allocation location of the next object in the heap.
CPU Register
This is basic computer knowledge. Review it here to help understand the following "root" concepts.
CPU registers are the CPU's own "temporary memory", which is faster than memory access. In order of distance from the CPU, the closest ones are registers, then cache (computer level one, level two, and level three cache), and finally memory.
Roots
Any static fields defined in the class, method parameters, local variables (only reference type variables), etc. are roots. In addition, the object pointers in the CPU register are also roots. Roots are the various entry points that the CLR can find outside of the heap.
Objects reachable and unreachable
If a root refers to an object in the heap, the object is "reachable", otherwise it is "unreachable".
The reason for garbage collection
From the perspective of computer composition, all programs must reside in memory and run. And memory is a limiting factor (size). In addition to this, the managed heap also has size limits. If there is no size limit on the managed heap, the execution speed of C# will be better than that of c (the structure of the managed heap allows it to allocate objects faster than the c runtime heap). Due to address space and storage limitations, the managed heap must maintain its normal operation through a garbage collection mechanism to ensure that objects are allocated without "memory overflow".
Basic principles of garbage collection
Recycling is divided into two stages: Marking –> Compression
The process of marking is actually the process of determining whether the object is reachable. When all roots have been checked, the heap will contain reachable (marked) and unreachable (unmarked) objects.
After marking is completed, enter the compression stage. During this phase, the garbage collector linearly traverses the heap to find contiguous blocks of memory for unreachable objects. And move reachable objects here to compact the heap. This process is somewhat similar to defragmenting disk space.
As shown in the picture above, the green box indicates reachable objects, and the yellow box indicates unreachable objects. After unreachable objects are cleared, moving reachable objects achieves memory compression (becoming more compact).
After compaction, the variables and CPU registers "pointers to these objects" are now invalid and the garbage collector must revisit all roots and modify them to point to the new memory locations of the objects. This can cause a significant performance penalty. This loss is also the main disadvantage of the managed heap.
Based on the above characteristics, the recycling algorithm caused by garbage collection is also a research topic. Because if you really wait until the managed heap is full before starting garbage collection, it will be really "slow".
Garbage Collection Algorithm – Generation Algorithm
Generation is a mechanism used by the CLR garbage collector. Its only purpose is to improve the performance of the application. Generational recycling is obviously faster than recycling the entire heap.
CLR managed heap supports 3 generations: Generation 0, Generation 1, and Generation 2. The space of generation 0 is about 256KB, generation 1 is about 2M, and generation 2 is about 10M. The newly constructed objects will be allocated to generation 0. As shown in the figure above, when the space of generation 0 is full, the garbage collector starts recycling, and unreachable objects (C and E in the figure above) will be recycled. , the surviving objects are classified as the 1st generation.
When the 0th generation space is full and the 1st generation also begins to have many unreachable objects and the space is almost full, then both generations of garbage will be recycled. For surviving objects (reachable objects), generation 0 is promoted to generation 1, and generation 1 is promoted to generation 2.
The actual CLR generation collection mechanism is more "intelligent". If the newly created object has a short life cycle, the 0th generation garbage will be recycled immediately by the garbage collector (without waiting for the space to be fully allocated). In addition, if generation 0 is recycled and it is found that there are still many objects "reachable" and

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics











Common memory management problems and solutions in C#, specific code examples are required. In C# development, memory management is an important issue. Incorrect memory management may lead to memory leaks and performance problems. This article will introduce readers to common memory management problems in C#, provide solutions, and give specific code examples. I hope it can help readers better understand and master memory management technology. The garbage collector does not release resources in time. The garbage collector (GarbageCollector) in C# is responsible for automatically releasing resources and no longer using them.

How to avoid memory leaks in C# development requires specific code examples. Memory leaks are one of the common problems in the software development process, especially when developing using the C# language. Memory leaks cause applications to take up more and more memory space, eventually causing the program to run slowly or even crash. In order to avoid memory leaks, we need to pay attention to some common problems and take corresponding measures. Timely release of resources In C#, resources must be released in time after use, especially when it involves file operations, database connections, network requests and other resources. Can

The development of artificial intelligence (AI) technologies is in full swing today, and they have shown great potential and influence in various fields. Today Dayao will share with you 4 .NET open source AI model LLM related project frameworks, hoping to provide you with some reference. https://github.com/YSGStudyHards/DotNetGuide/blob/main/docs/DotNet/DotNetProjectPicks.mdSemanticKernelSemanticKernel is an open source software development kit (SDK) designed to integrate large language models (LLM) such as OpenAI, Azure

Memory management in Java involves automatic memory management, using garbage collection and reference counting to allocate, use and reclaim memory. Effective memory management is crucial for security because it prevents buffer overflows, wild pointers, and memory leaks, thereby improving the safety of your program. For example, by properly releasing objects that are no longer needed, you can avoid memory leaks, thereby improving program performance and preventing crashes.

Whether you are a beginner or an experienced professional, mastering C# will pave the way for your career.

Summary of memory management problems and solutions encountered in Python development: In the Python development process, memory management is an important issue. This article will discuss some common memory management problems and introduce corresponding solutions, including reference counting, garbage collection mechanism, memory allocation, memory leaks, etc. Specific code examples are provided to help readers better understand and deal with these issues. Reference Counting Python uses reference counting to manage memory. Reference counting is a simple and efficient memory management method that records every

How to use Go language for memory optimization and garbage collection. As a high-performance, concurrent, and efficient programming language, Go language has good support for memory optimization and garbage collection. When developing Go programs, properly managing and optimizing memory usage can improve the performance and reliability of the program. Use appropriate data structures In the Go language, choosing the appropriate data structure has a great impact on memory usage. For example, for collections that require frequent additions and deletions of elements, using linked lists instead of arrays can reduce memory fragmentation. in addition,

Analysis of Python's underlying technology: How to implement the garbage collection mechanism requires specific code examples Introduction: Python, as a high-level programming language, is extremely convenient and flexible in development, but its underlying implementation is quite complex. This article will focus on exploring Python's garbage collection mechanism, including the principles, algorithms, and specific implementation code examples of garbage collection. I hope that through this article’s analysis of Python’s garbage collection mechanism, readers can have a deeper understanding of Python’s underlying technology. 1. Principle of garbage collection First of all, I
