Thursday, June 6, 2013

Heap Memory management in .Net

Heaps are used to store reference type objects, the .Net runtime uses types of heaps to store objects.

Small object Heap: Used to store objects with size < 85K Bites
Large object Heap: Used to store objects with size > 85K Bites.

Heaps are used to store reference types like classes, objects, delegates etc. based on the size of the object the runtime decides where to place the object, either in the small object heap or large object heap.
When an instance of a class is created, the actual object is stored in the Heap and a reference to that object is stored in the stack frame used to execute the method.

The stack collectively holds all the values and references required to execute the program. If the type is a value type then the Stack holds it directly, if the type is a reference type then it is placed in the Heap and the stack holds a reference to the type, hence the Stack has the total control over the program execution while the Heap is just used as a storage location to store reference type objects.

When one instance of a class is assigned to another instance of the same class, only copy of the object is stored in the Heap while 2 separate references are stored in the Stack. The following example explains this.

clsEmploee objEmployee1 = new clsEmployee();
clsEmploee objEmployee2 = new clsEmployee();
objEmployee2 = objEmployee1;

When the above lines of code get executed there will be only one object stored in the Heap, but there will  be 2 references in the Stack, both pointing to the same object in the Heap. The original object assigned to objEmployee2 will get erased, and both references will be pointing to the object which was originally created for objEmployee1.

Search Flipkart Products:
Flipkart.com

No comments: