none
Why is it not possible to predict when garbage collection will occur ? RRS feed

  • Question

  • Hello,

    I was just studying about IDisposable interface .

    This is the MSDN link where i was referring :

    http://msdn.microsoft.com/en-us/library/system.idisposable.aspx

    You can see , there it is said that it is not possible to predict when garbage collection will occur .

    Hae...really this is interesting !! can someone please explain its reason ?

    Thursday, January 5, 2012 6:00 PM

Answers

  • Garbage collection happens based on many factors - including the memory pressure on the machine at the time.  It's designed to be non-deterministic, as allowing the system to manage when (and if!) it collects memory increases overall performance.

     

    The thing with a GC is that it's all about balancing between opposing goals - collecting more often means less performance (collections aren't cheap) but uses less overall memory.  Collecting very rarely improves performance,  but can lead to using too much memory.  The GC tries to balance this using some very complex heuristics.

     

    As such, you can reasonably assume that your object will get collected at some point after being unrooted, but it's not safe to assume that it will be collected at any specific point in time.  While you can force this (by calling GC.Collect), doing so messes up the internal heuristics and is not recommended - most of the time, it causes many more problems than it solves.

     


    Reed Copsey, Jr. - http://reedcopsey.com
    If a post answers your question, please click "Mark As Answer" on that post and "Mark as Helpful".
    • Marked as answer by Shyam Kr Thursday, January 5, 2012 7:02 PM
    Thursday, January 5, 2012 6:23 PM
    Moderator