Wednesday, March 17, 2010
GARBAGE COLLECTION ON VALUE AND REFERENCE TYPES.
Garbage collection or memory manager in .net ...there is a very good video at the end...that is the best I have seen for understanding garbage collection..
There was one very nice article that i read felt to write this blog post so that i can have a record of what i understood. This is a very small topic and most of the people know it, but slowly tend to forget it as dust falls on the memory tape.
First and foremost, garbage collection does not happen for value types, it is only done for reference types if you know why ? (you need not read on) : (else go ahead....cheers)
Value types have their own value where as reference types have reference to the value and not the actual value directly. So now is this the reason why garbage collection is not done for value type?
No the reason why GC is not done for value types lies in the memory that they are allocated on.
Value types are allocated on the stack, so they are created when a method is invoked and when the method execution is completed the memory taken up by the variables on the stack is freed, so there is no need for GC on value types.
Now why is GC needed for reference types..
When you create an instance of the reference type they are allocated on the stack like Value types are, but they point to a value for getting their actual value which is sitting on the Managed heap (fig). You know from reading above that the stack variables are removed after the method execution is completed, but the actual value sitting on the managed heap which was referenced by the reference type variable instance is still sitting on the Managed Heap. Now this is how GC checks the managed heap objects whether there are any references left on the Stack that use this value on the Managed Heap if there is nothing it is freed.
Basically Garbage Collection is a two step process 1) it finalizes object that are no more referenced and in the next GC cycle the memory is freed.
Hope you understood and felt as good as i felt after reading the article...Knowing something well makes us happy and confident.
Posted by balakrishna t