Tuesday, July 17, 2012

Garbage Collector - SuppressFinalize Method

Using finalize/destructor leads to more objects in Gen 1 and Gen 2

The C# compiler translates (renames) the destructor into Finalize. If you see the IL code using IDASM you can see that the destructor is renamed to finalize. So let’s try to understand why implementing destructor leads to more objects in gen 1 and gen 2 regions. Here’s how the process actually works:-

• When new objects are created they are moved to gen 0.
• When gen 0 fills out GC runs and tries to clear memory.
• If the objects do not have a destructor then it just cleans them up if they are not used.
• If the object has a finalize method it moves those objects to the finalization queue.
• If the objects are reachable it’s moved to the ‘Freachable’ queue. If the objects are unreachable the memory is reclaimed.
• GC work is finished for this iteration.
• Next time when GC again starts its goes to Freachable queue to check if the objects are not reachable. If the objects are not reachable from Freachable memory is claimed back.

In other words objects which have destructor can stay more time in memory. 


• Do not have empty destructors in your classes.
• In case you need to clean up use finalize dispose pattern with ‘SupressFinalize’ method called.
• If there is a dispose method exposed by a class , ensure to call the same from your client code.
• Application should have more objects allocated in Gen 0 than Gen 1 and Gen 2. More objects in Gen 1 and 2 is sign of bad GC algorithm execution.

No comments: