Low Memory Garbage Collection


#1

I’ve been looking into how garbage collector behaves in low memory environment. If I understand correctly, the GC uses CreateMemoryResourceNotification to subscribe to OS notification when it’s low on memory. It then calls, GCHeapUtilities::GetGCHeap()->GarbageCollect(0, TRUE);.

What I don’t understand is, why is it doing generation 0 garbage collection? I would expect that in low memory case, it would try to reclaim as much memory as possible, and thus run a generation 2 garbage collection.

I tried writing a test application that allocates around 512MB on managed heap (in chunks of 64kb, to avoid Large Object Heap allocation), and then releases all references to it. If I manually call GC.Collect(2), it releases everything I allocated. If I cause low memory situation, it does nothing. I have verified with debugger, that garbage collector gets called.


#2

Hello there.
From what i understand the gc algorithm works like this.

  1. Low memory notification
  2. GC will collect the generation 0
  3. If the collection of the generation 0 was not enough the GC will procceed with the generation 1, 2 and 3.

Side note: The collection of every generation has a performance cost.
The generation 0 has the lowest impact and the generation 3 has the highest impact.

This happens because the generation 0 is the newest and the lowest on risk. (If the objects stayed on the generation 0 its because they are not important or they are recently allocated.)

The generation 1 is the stack of objects that were on generation 0 and lived long enough (or survived from a GC.Collect)

The same goes for the generation 2 but this time the stack of objects were on generation 1.

The generation 3 is a special generation that holds large objects and will get collected as a last resort.

You can find more information about this on the Book Of runtime - Garbage Collection.

Thanks.


.NET Foundation Website | Blog | Projects | Code of Conduct