Garbge Collection and ActionScript

Performance has been a buzzword for all of us who are into writing super fast applications and with Flash games it has been more so important. As, I started to move into Flex, this was one of areas that I wanted to get a hang on real fast. No one wants, to write code that is not per formant and no one wants to come back and fix code that is not performing.

So, in came Garbage collection in Action script, and I tried a simple and very straight forward spike. I created two buttons and placed then in a Canvas. Then on click on a button i removed the other button. I kept on checking on for quite some time, if the GC had collected the resources, but it did not.

Lesson 1: Garbage Collector does not run as soon as you remove a control. It will run when it is needed. It will check upon system resources like available memory, stack, heap and decide when to collect.

It dawned upon me how would then I know when it collects and how do I optimize or in other words how do I make sure that when a GC collects, it will find what I want to destroy. Complicating the scenario, this is an issue when you have many screens in the application as re-usable objects (creating modules and that can be reused. So, a strategy that comes to mind is what I learned in ASP.NET to have an initialize() and destroy() methods. When I want to load the view for the first time (create) or navigate back in, then i use the initialize() to add all event listeners and when I navigate out, then use the “destroy()” to remove all the events listeners.

This keeps things really simple and also ensures that you will not end up have memory hogged.

Lesson 2: Make sure that you are cleaning up your trail as you move on. Do not leave bread crumbs for monsters to catch up.

I am still learning, so I will continue to post more.


3 thoughts on “Garbge Collection and ActionScript

  1. Like the runtime in C# or Java, Garbage Collection is really run in an ad-hoc manner. What happens is it looks for any objects in memory that don’t have anything pointing to them. For example, if I create a new button, and the stage that that button then is no longer in use, that button’s object in memory no longer has anything pointing to it. Another way to make sure something is noticed by the garbage collection is to set its variable to null.

    For example : myButton = null;

    While we can’t force the GC to start, next time it runs, it will see that what myButton was pointing to is no longer in use, and it will clean it up.

Initiate your idea here...

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

You are commenting using your 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