官术网_书友最值得收藏!

Generations in GC

There are three kinds of generation in garbage collection known as Generation 0, Generation 1, and Generation 2. In this section, we will look at the concept of generations and how it affects the performance of the garbage collector.

Let's suppose we run an application that creates three objects named Object1, Object2, and Object3. These objects will allocate the memory in Generation 0:

Now, when the garbage collector runs (this is an automatic process, unless you explicitly call the garbage collector from the code), it checks for the objects that are not needed by the application and have no reference in the program. It will simply remove those objects. For example, if the scope of Object1 is not referenced anywhere, the memory for this object will be reclaimed. However, the other two objects, Object1 and Object2, are still referenced in the program, and will be moved to Generation 1.

Now, let's suppose two more objects, called Object4 and Object5, are created. We will store them in the Generation 0 slot, as shown in the following diagram:

When garbage collection runs the second time, it will find two objects called Object4 and Object5 in Generation 0 and two objects called Object2 and Object3 in Generation 1. Garbage collector will first check the reference of those objects in Generation 0 and, if they are not used by the application, they will be removed. The same goes for the Generation 1 objects. For example, if Object3 is still referenced, it will be moved to Generation 2 and Object2 will be removed from Generation 1, as shown in the following diagram:

This concept of generations actually optimizes the performance of GC, and the objects stored in Generation 2 are more likely to be stored for a longer period. GC performs fewer visits and gains time instead of checking each object again and again. The same goes for Generation 1, which is also less likely to reclaim the space than Generation 0.

主站蜘蛛池模板: 元朗区| 宁德市| 福建省| 松潘县| 同德县| 封开县| 即墨市| 阿图什市| 岑巩县| 江源县| 广汉市| 黑山县| 萨嘎县| 绍兴县| 罗田县| 湟源县| 泽州县| 怀集县| 吴旗县| 闻喜县| 莱芜市| 济阳县| 福贡县| 鸡泽县| 宜城市| 岑巩县| 广汉市| 玉树县| 梁平县| 临沭县| 荆门市| 日照市| 南阳市| 上犹县| 南召县| 绥棱县| 东辽县| 固阳县| 宽甸| 河北区| 连山|