Wednesday, March 17, 2010


Explains how garbage collector works with Value type and Reference type, for cleaning up the memory.

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 slowely 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.

And this Video if you have time explains things in great detail , I understood GC very well after seeing this video.

Bye...Keep rocking

No comments:

Post a Comment