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.