Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why Garbage collector have only 3 generations, not more or less?

Tags:

c#

.net

As i have gone through Garbage Collection (GC) and its generation(0,1,2). The question strikes to me that, why Microsoft decided to keep it to 3?

Why not to less than 3 or more than 3 ? I need some logical explanation.

like image 441
Sandeep Rasgotra Avatar asked Sep 07 '25 10:09

Sandeep Rasgotra


1 Answers

Quoting the documentation,

Generations

The heap is organized into generations so it can handle long-lived and short-lived objects. Garbage collection primarily occurs with the reclamation of short-lived objects that typically occupy only a small part of the heap. There are three generations of objects on the heap:

Generation 0.

This is the youngest generation and contains short-lived objects. An example of a short-lived object is a temporary variable. Garbage collection occurs most frequently in this generation.

Newly allocated objects form a new generation of objects and are implicitly generation 0 collections, unless they are large objects, in which case they go on the large object heap in a generation 2 collection.

Most objects are reclaimed for garbage collection in generation 0 and do not survive to the next generation.

Generation 1.

This generation contains short-lived objects and serves as a buffer between short-lived objects and long-lived objects.

Generation 2.

This generation contains long-lived objects. An example of a long-lived object is an object in a server application that contains static data that is live for the duration of the process.

Garbage collections occur on specific generations as conditions warrant. Collecting a generation means collecting objects in that generation and all its younger generations. A generation 2 garbage collection is also known as a full garbage collection, because it reclaims all objects in all generations (that is, all objects in the managed heap).

We can see that Generation 2 is for objects that should last for the duration of the process. It is not sensible to model objects that can live longer than the process, at least on operating systems I know about.

I suspect that there is not a greater granularity of generations because it would prove more cumbersome than the benefits derived. Any extrapolation on that concept is pure conjecture without real world performance testing.

I suspect even a canonical answer from a designer of the GC would be prone to speculation but they may be able to detail how that level of granularity was reckoned.

like image 67
Jodrell Avatar answered Sep 10 '25 02:09

Jodrell