.NET 垃圾收集器基础知识 [英] .NET Garbage Collector Basics

查看:29
本文介绍了.NET 垃圾收集器基础知识的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果这个问题的答案是微不足道的,我深表歉意.但我仍然无法自己弄清楚这一点.

I apologize if the answer to this question is trivial. But I still cannot figure out this by myself.

.NET 中的垃圾收集器如何识别堆上哪些对象是垃圾,哪些对象不是?

How does the garbage collector in .NET identify what objects on the heap are garbage and what objects are not?

假设一个 .NET 应用程序正在运行,并且在某个时间点发生垃圾收集(为了简单起见,让我们省略代和终结队列).

Lets say a .NET application is running and at a certain point of time garbage collection occurs(lets leave out the generations and finalization queue for simplicity sake).

现在应用程序可能有:

  1. 指向堆上对象的堆栈变量.
  2. 包含堆上对象地址的寄存器.
  3. 指向堆上对象的静态变量.

这就是我假设 GC 的工作方式.

This is how I ASSUME the GC works.

  1. 它取消引用每个这样的地址,并在堆上的对象处结束.
  2. 它将对象标记为非垃圾对象(通过使用同步块索引),因为某些变量仍然指向它.
  3. 它对所有地址(在大多数文章中出于某种原因称为根)执行此操作
  4. 现在,由于 .NET 运行时有关于每个对象的 TYPE 的信息,它可以计算每个对象的大小,从而计算它占用的堆内存块.对于所有被标记的对象,它保留原样占用的内存块.
  5. 剩余的内存被释放、压缩,如有必要,其他对象将被重新定位(并更新它们的地址).

我的理解是否正确?

推荐答案

在某些情况下您是对的.GC 悲观地查看堆 - 即它假设所有内容(在第 0 代中)都将被 GC.

You are right in some cases. The GC looks through the heap pessimistically - i.e. it sets off assuming everything (in Generation 0) will be GCed.

它实际上通过称为标记"的第一次扫描遍历堆上的所有内容,其中检查是否有任何内容引用它.由于它们都是引用类型并且一些引用其他类型,因此它将递归导航引用.别担心 - 有逻辑不会进入无限循环!

It literally goes through everything on the heap through a first sweep called "marking", in which is checks if anything is referencing it. Since they are all reference types and some reference others, it will recursively navigate the references. Don't worry - there is logic to not get into an infinite loop!

如果它发现一个对象没有被引用,它会首先通过在对象中设置一个称为同步块索引的标志来标记它.

If it finds an object is not referenced, it will firstly mark it, by setting a flag within the object called the sync block index.

在遍历完堆上的每个对象后,它将开始一个称为压缩"的过程,即将所有剩余的对象移动到相同的内存区域中,从而清除上面的内存.它会将同一代的对象保持在一起,因为它们在统计上更有可能同时被取消引用.

After going through every object on the heap, it will then begin a process called "compacting" which is when it shifts all of the remaining objects into the same area of memory, leaving the memory above clear. It will keep the objects of the same generation together as they are statistically more likely to be de-referenced at the same time.

因此,这将减少所需的内存.

This therefore will reduce the memory needed.

垃圾收集不一定会加速您的程序,但确实允许它重新使用未使用对象占用的空间.

Garbage Collection doesn't necessarily speed up your program, but does allow it to re-use the space occupied by unused objects.

关于这个主题的文章很多.我个人喜欢 Jeffrey Richter 的通过 C# 实现 CLR",他对它的工作原理作了精彩的介绍.

There are many many articles on the subject. I personally like "CLR via C#" by Jeffrey Richter who gives an excellent chapter on how it works.

这篇关于.NET 垃圾收集器基础知识的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆