One of the most common problems with Flash applications are memory leaks, programming flaws that cause Flash Player to loose access to memory that it could recycle otherwise. In the mobile space it’s crucial to understand memory management to get the most out of the Flash Player, and ultimately to ensure a smooth ride for your consumers.
Flash Player memory management
Flash Player makes use of automatic memory management, to help you to create applications with ease and with less code. In fact the Flash Player uses a pretty simple mechanism that determines how many times you have referenced a particular object. Once an object has nothing referencing it then it can be garbage collected – predictably it’s called “reference counting”.
The following is a great example of reference counting in action, notice that I have created a Geolocation object (geo) and added updateHandler as a listener function for update events. This counts as a reference against updateHandler:
var geo:Geolocation = new Geolocation();
The updateHandler function marks the location object null, tagging it for deletion by the garbage collector which is great. The problem is that the location object still has a reference to updateHandler, and therefore the location object cannot be deleted until that function looks like this:
Memory leaks are easy to create in Flash, and even harder to debug later. It’s therefore essentially to build your applications with memory in mind and use all tools at your disposal to keep checking for leaks, slow performance, and run away code.
Flash Builder Profiler
Flash Builder 4 ships with a new feature called the Profiler and in the video below I’ll show you how to use it to solve a memory leak. Now don’t be fooled, this memory leak took a few hours to solve in reality – these aren’t easy problems to solve.
In fact I found two memory leaks, the first is the ExternalInterface.addCallback holding onto a function reference. The other is more complex, and I have marked it “Flash Player Bug” as I believe this is a problem with the runtime itself.