In an interview, the interviewer asked me the following :
Lets assume the Gen 0 is of size 5 kb and the object which I am creating is of size 20 kb, what will happen ?
I answered that the CLR will expand the Gen 0 region .
Now I am confused whether it is the right answer or not.
Is it correct?
Generation 0 identifies a newly created object that has never been marked for collection. Generation 1 identifies an object that has survived a GC (marked for collection but not removed because there was sufficient heap space) Generation 2 identifies an object that has survived more than one sweep of the GC.
A generation 2 garbage collection is also known as a full garbage collection, because it reclaims objects in all generations (that is, all objects in the managed heap).
After the CLR initialized, objects which are first added to the managed heap are defined as Gen0. When the GC executed, the generation of the objects which were not collected will increase by 1 level and became Gen1. Objects created after that are still Gen0.
You'll end up with Gen 0 of 25K, unless something crazy happens (like another thread allocating a bunch of memory or GC getting trigged because the other generations are too big).
The budget for Gen 0 is generally much bigger than 25k (default is 256K), so allocating that amount won't do anything special. The object itself isn't bigger than 85K, so it won't end up in the Large Object Heap either.
The numbers (5K and 20K) a bit weird, since they aren't anywhere near the thresholds for anything interesting to happen.
The exact specifics depend on the implementation and can vary slightly between framework versions. Gen0 and Gen1 are not intended to grow, while Gen2 can grow indefinitely. Bursting the limits of Gen0 and 1 will normally trigger a collection.
Generation 1 and 0 live in something called the ephemeral segment (the first small object segment in each heap) and the size of Gen 1 and Gen 0 can never exceed the size of a segment. If a new segment is created that will become the new ephemeral segment. Gen 2 on the other hand can grow indefinitely (or until you run out of memory) so if you have high memory consumption a large amount of your objects will live in Gen 2.
In my experience with large ETL processes, large data objects tend to get allocated to Gen2 fairly quickly, and Gen2 garbage collection is relatively infrequent so those objects can stick around for some time.
The article How does the GC work and what are the sizes of the different generations? gives a great overview of this along with some related links.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With