search
HomeBackend DevelopmentC#.Net Tutorial.net garbage collection (GC) principle

.net garbage collection (GC) principle

Nov 26, 2016 am 10:22 AM
.netGarbage 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
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
Developing with C# .NET: A Practical Guide and ExamplesDeveloping with C# .NET: A Practical Guide and ExamplesMay 12, 2025 am 12:16 AM

C# and .NET provide powerful features and an efficient development environment. 1) C# is a modern, object-oriented programming language that combines the power of C and the simplicity of Java. 2) The .NET framework is a platform for building and running applications, supporting multiple programming languages. 3) Classes and objects in C# are the core of object-oriented programming. Classes define data and behaviors, and objects are instances of classes. 4) The garbage collection mechanism of .NET automatically manages memory to simplify the work of developers. 5) C# and .NET provide powerful file operation functions, supporting synchronous and asynchronous programming. 6) Common errors can be solved through debugger, logging and exception handling. 7) Performance optimization and best practices include using StringBuild

C# .NET: Understanding the Microsoft .NET FrameworkC# .NET: Understanding the Microsoft .NET FrameworkMay 11, 2025 am 12:17 AM

.NETFramework is a cross-language, cross-platform development platform that provides a consistent programming model and a powerful runtime environment. 1) It consists of CLR and FCL, which manages memory and threads, and FCL provides pre-built functions. 2) Examples of usage include reading files and LINQ queries. 3) Common errors involve unhandled exceptions and memory leaks, and need to be resolved using debugging tools. 4) Performance optimization can be achieved through asynchronous programming and caching, and maintaining code readability and maintainability is the key.

The Longevity of C# .NET: Reasons for its Enduring PopularityThe Longevity of C# .NET: Reasons for its Enduring PopularityMay 10, 2025 am 12:12 AM

Reasons for C#.NET to remain lasting attractive include its excellent performance, rich ecosystem, strong community support and cross-platform development capabilities. 1) Excellent performance and is suitable for enterprise-level application and game development; 2) The .NET framework provides a wide range of class libraries and tools to support a variety of development fields; 3) It has an active developer community and rich learning resources; 4) .NETCore realizes cross-platform development and expands application scenarios.

Mastering C# .NET Design Patterns: From Singleton to Dependency InjectionMastering C# .NET Design Patterns: From Singleton to Dependency InjectionMay 09, 2025 am 12:15 AM

Design patterns in C#.NET include Singleton patterns and dependency injection. 1.Singleton mode ensures that there is only one instance of the class, which is suitable for scenarios where global access points are required, but attention should be paid to thread safety and abuse issues. 2. Dependency injection improves code flexibility and testability by injecting dependencies. It is often used for constructor injection, but it is necessary to avoid excessive use to increase complexity.

C# .NET in the Modern World: Applications and IndustriesC# .NET in the Modern World: Applications and IndustriesMay 08, 2025 am 12:08 AM

C#.NET is widely used in the modern world in the fields of game development, financial services, the Internet of Things and cloud computing. 1) In game development, use C# to program through the Unity engine. 2) In the field of financial services, C#.NET is used to develop high-performance trading systems and data analysis tools. 3) In terms of IoT and cloud computing, C#.NET provides support through Azure services to develop device control logic and data processing.

C# .NET Framework vs. .NET Core/5/6: What's the Difference?C# .NET Framework vs. .NET Core/5/6: What's the Difference?May 07, 2025 am 12:06 AM

.NETFrameworkisWindows-centric,while.NETCore/5/6supportscross-platformdevelopment.1).NETFramework,since2002,isidealforWindowsapplicationsbutlimitedincross-platformcapabilities.2).NETCore,from2016,anditsevolutions(.NET5/6)offerbetterperformance,cross-

The Community of C# .NET Developers: Resources and SupportThe Community of C# .NET Developers: Resources and SupportMay 06, 2025 am 12:11 AM

The C#.NET developer community provides rich resources and support, including: 1. Microsoft's official documents, 2. Community forums such as StackOverflow and Reddit, and 3. Open source projects on GitHub. These resources help developers improve their programming skills from basic learning to advanced applications.

The C# .NET Advantage: Features, Benefits, and Use CasesThe C# .NET Advantage: Features, Benefits, and Use CasesMay 05, 2025 am 12:01 AM

The advantages of C#.NET include: 1) Language features, such as asynchronous programming simplifies development; 2) Performance and reliability, improving efficiency through JIT compilation and garbage collection mechanisms; 3) Cross-platform support, .NETCore expands application scenarios; 4) A wide range of practical applications, with outstanding performance from the Web to desktop and game development.

See all articles

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

Hot Tools

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

SublimeText3 Linux new version

SublimeText3 Linux new version

SublimeText3 Linux latest version

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.

MinGW - Minimalist GNU for Windows

MinGW - Minimalist GNU for Windows

This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

DVWA

DVWA

Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software