Friday, July 8, 2011
Stack vs Heap memory
Stack
Stack memory stores variable types in address' in memory, these variables in programming are called local variables and are often stored for short amounts of time while a function/method block uses them to compute a task.
Once a function/method has completed its cycle the reference to the variable in the stack is removed.
Heap
Heap memory stores all instances or attributes, constructors and methods of a class/object.
Comparison
A Heap reference is also stored in Stack memory until the life cycle of the object has completed. Inside the Heap reference all the the contents of the object are stored whereas with a local variable only the variable contents are stored in the stack.
Example:
Stack
var blue
var red
ref 0x456783 (Heap reference)
var tom
ref 0x498702 (Heap reference)
var diane
Heap (0x456783)
name => Susan
age => 26
city => London
height => 5'7
sex => female
Heap (0x498702)
name => Paul
age => 21
city => Glasgow
height => 6'0
sex => male
Subscribe to:
Post Comments (Atom)
Variable types are stored in addresses in stack memory. These are the variable declared locally in functions for a small time intervals. Once the function is complete the reference is released from the stack.
ReplyDeleteMethods, constructors and instance are stored in the heap memory. eg. in C malloc can be used to allocate heap memory.
Stack also stores references to these heaps for the time these methods and objets are used. once the object is no more used these references are also freed.