Search code examples
c#garbage-collectionheap-memory

C# Garbage collection


Say we have:

public void foo()
{
   someRefType test = new someRefType ();
   test = new someRefType ();
}

What does the garbage collector do with the first heap object? Is it immediately garbage collected before the new assignment? What is the general mechanism?


Solution

  • What does the garbage collector do with the first heap object?

    Who knows? It's not deterministic. Think of it like this: on a system with infinite memory, the garbage collector doesn't have to do anything. And you might think that's a bad example, but that's what the garbage collector is simulating for you: a system with infinite memory. Because on a system with sufficiently more memory available than required by your program, the garbage collector never has to run. Consequently, your program can not make any assumptions about when memory will (if ever) be collected.

    So, the answer to your question is: we don't know.

    Is it immediately garbage collected before the new assignment?

    No. The garbage collector is not deterministic. You have no idea when it will collect and release garbage. You can not make any assumptions about when garbage will be collected or when finalizers will run.

    In fact, it's very unlikely it's collected so quickly (that would make collections happen too frequently). Additionally, on a system with sufficient memory, the garbage collector never has to run.

    What is the general mechanism?

    That's a fairly broad question. But the underlying principle is very simple: a garbage collector simulates a machine with infinite memory. To do this, it somehow keeps track of memory and is able to determine when memory is garbage. When it sees fit, due to its need to simulate infinite memory, it will from time to time collect this garbage and make it available for allocation again.