Home Backend Development C#.Net Tutorial .net garbage collection (GC) principle

.net garbage collection (GC) principle

Nov 26, 2016 am 10:22 AM
.net Garbage collection

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.

.net garbage collection (GC) principle

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.

.net garbage collection (GC) principle

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.

.net garbage collection (GC) principle

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.

.net garbage collection (GC) principle

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 .net garbage collection (GC) principle

has not released much memory, the budget of generation 0 will be increased to 512KB, and the recycling effect will be transformed into: the number of garbage collections will be reduced, but a large amount of memory will be reclaimed each time. If not much memory has been released, the garbage collector will perform a

full collection (3 generations), and if it is still not enough, a "memory overflow" exception will be thrown.

In other words, the garbage collector will dynamically adjust the allocated space budget of each generation based on the size of the recovered memory! Achieve automatic optimization!

Summary

There is a basic idea behind garbage collection: programming languages ​​(most of them) always seem to have access to unlimited memory. And developers can keep allocating, allocating, and allocating—like magic, inexhaustible.

The basic working principle of the .NET garbage collector is: clear unreachable objects through the most basic mark and clear principle; then compress and organize available memory like disk defragmentation; and finally optimize performance through generational algorithms.

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

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

Hot Article

Roblox: Bubble Gum Simulator Infinity - How To Get And Use Royal Keys
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Nordhold: Fusion System, Explained
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Mandragora: Whispers Of The Witch Tree - How To Unlock The Grappling Hook
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Hot Topics

Java Tutorial
1670
14
PHP Tutorial
1274
29
C# Tutorial
1256
24
Common memory management problems and solutions in C# Common memory management problems and solutions in C# Oct 11, 2023 am 09:21 AM

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 How to avoid memory leaks in C# development Oct 08, 2023 am 09:36 AM

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

Share several .NET open source AI and LLM related project frameworks Share several .NET open source AI and LLM related project frameworks May 06, 2024 pm 04:43 PM

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

What is the relationship between memory management techniques and security in Java functions? What is the relationship between memory management techniques and security in Java functions? May 02, 2024 pm 01:06 PM

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.

What are the employment prospects of C#? What are the employment prospects of C#? Oct 19, 2023 am 11:02 AM

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

Memory management problems and solutions encountered in Python development Memory management problems and solutions encountered in Python development Oct 09, 2023 pm 09:36 PM

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 How to use Go language for memory optimization and garbage collection Sep 29, 2023 pm 05:37 PM

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 garbage collection mechanism Analysis of Python's underlying technology: how to implement garbage collection mechanism Nov 08, 2023 pm 07:28 PM

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

See all articles