.net - 垃圾回收分为哪几代?

标签 .net garbage-collection

我不明白垃圾收集上下文中的“世代”是什么。谁能简单解释一下?

最佳答案

来自Understanding Garbage Collection in .NET

Generations

A generational garbage collector collects the short-lived objects more frequently than the longer lived ones. Short-lived objects are stored in the first generation, generation 0. The longer-lived objects are pushed into the higher generations, 1 or 2. The garbage collector works more frequently in the lower generations than in the higher ones.

When an object is first created, it is put into generation 0. When the generation 0 is filled up, the garbage collector is invoked. The objects that survive the garbage collection in the first generation are promoted onto the next higher generation, generation 1. The objects that survive garbage collection in generation 1 are promoted onto the next and the highest generation, generation 2. This algorithm works efficiently for garbage collection of objects, as it is fast. Note that generation 2 is the highest generation that is supported by the garbage collector.

Garbage Collection in .NET

Generations

While memory allocation on the managed heap is fast, GC itself may take some time. With this in mind several optimisations have been made to improve performance. The GC supports the concept of generations, based on the assumption that the longer an object has been on the heap, the longer it will probably stay there. When an object is allocated on the heap it belongs in generation 0. Each garbage collection that that object survives increases its generation by 1 (currently the highest supported generation is 2). Obviously it's faster to search through, and garbage collect a subset of all objects on the heap, so the GC has the option of collecting only generation 0, 1 or 2 objects (or whatever combination it chooses until it has sufficient memory). Even while collecting only younger objects the GC can also determine if old objects have references to new objects to ensure that it doesn't inadvertently ignore in-use objects.

关于.net - 垃圾回收分为哪几代?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2257563/

相关文章:

java - GCViewer模式分析

java - 本地创建的对象被另一个全局对象引用时会发生什么

c# - 如何使用 .Net (C#) 在服务器端将原始 HTML 转换为 Markdown?

c# - 关于垃圾收集 C# .NET 的问题

c# - List<T>.Insert 与 Stack<T>.Push

c# - 如何等待 ThreadState.Abort?

linux - 在 linux 系统上拥有高 pgfree/s 有什么意义?

java - 如何找到哪些对象产生的垃圾最多

c# - O(1) 哈希查找?

c# - 无法在 GetTypes 方法上加载文件或程序集错误