Pushing the boundaries

…couldn’t be any simpler!

Stacks and Heaps

Posted by vijayram on January 30, 2007

Someone asked me this question and I wasn’t in the best position to reply back then. This time I will take the effort of writing it down for future reference and for the benefit of all.

Simple explanation would be, stack is allocated before the program executes, where the heap contains memory allocated during the program run.

Using ActionScript for Flash, you can keep track of how much memory Flash Player uses at run-time using the System.totalMemory method.

To begin with data can be of two types, Value or Reference. Although there are many data types, they are always treated: as primitive (also called Value) and by Reference. It is important to note where this data is stored. Value types are stored in “stack” and Reference types are stored in the “heap”. Lets look at this way, objects created on the fly(ie: using the “new” keyword) is stored in the heap while variables will be stored in the stack.

Both Stack and Heap work together. Stack works on basis of last-in, first-out (LIFO). This would be the top-most in the pile would be removed first. Once an object has been instantiated from a class, it is moved into the heap.

During the course of the program running, the heap is polluted with unused data reference which doesn’t exist anymore. This is when the Garbage Collector kicks in. It is the role of the Garbage Collector to clear the heap of unused references or data, else you will have a memory leak, causing the program to come to a grinding halt!

Garbage Collector which is part of the ActionScript Virtual Machine uses several techniques to clear up the data of the heap. There is a “reference counting” technique and there is also a “mark and sweep” technique. From my understanding Garbage Collector in Flash Player 9 uses a deferred method whereby, based on certain factors, the Garbage Collector will kick-in and not by merrily removing the reference to the object in code clears up the heap.

Technorati Tags: , , ,

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

 
%d bloggers like this: