Tuesday, September 23, 2008

Memory concepts at runtime

We have two kind of memorys.
1) Heap Memory
2)Stack Memory.

Usually the variables might be value or referneced type should be stored in a memory to access.

As there are 2 different memories there sholud be set of rules defined where to store these variables.


a) When we try to create an object in runtime they will created inside heap memory.
But the reference type variable refering to this object can be in heap or stack. To explain when they will be in stack or heap we should be aware with the
following concepts.

i) A variable can be declared inside a function or as a variable member to a class.

The above mentioned line is vital while considering memory management.
A variable declared as local in a function will be stored in stack where as declared as a variable member in a class will be stored in heap.

So that is why it is recommended to use a very less global variables in a class whose memory gets created in heap memory.

So for stack memory it is not required to trap memory cleaning, but for heap memory we have (GC) garbage collector which should run algorithm for cleaning the
heap memory.

b) Static funtions and variable will always be created in heap memory which will created only once but not for every instance of the class.

c) Instance functions get loaded into stack memory so when a function gets called by another , as soon as called function is completed it will be removed from
stack memory, obviously relevant variables will be removed from stack.

d) A refernce type variable pointing to a object is also declared as variable members to class then that refernce type variable along with its pointing object will be stored in heap memory.

So we should be sure about the variable (reference or value) that we declare is according to set of rules defined above.

No comments: