Memory Leak Unit Test
Posted: January 7th, 2008 | Author: nuno | Filed under: Actionscript3, Adobe Flex | 3 Comments »(or Programmatically Detecting Memory Leaks in AS3 via Unit Tests)
I've been writing unit tests for a class that deals with the loading/unloading of different types of media files. One of the tests I would like to have is a check for memory leaks. This is especially important now that we have automated our builds, so we can known instantly if a new change in the code doesn't break the behavior we're expecting.
A memory leak occurs when an unintentional memory consumption occurs. That means we were expecting the garbage collector (GC) to run and clean some resources from memory but for some reason (e.g. lost reference or listener) the GC was unable to remove it from memory.
I read from Skinner here that: "The GC uses a set of heuristics that look at RAM allocation and the size of the memory stack (among other things) to determine when to run".
That means we don't know when the GC will run and clean our resources from memory, which makes it hard to test something like this. But there are two ways ([2] and [3]) to force the GC to run so we can use that to test that something that should have been cleaned from memory is really removed from memory.
I did some code already (using Flexunit) and what I'm doing is creating a set of instances of the class I want to test which is the same as saying loading a bunch of images into memory. I then delay a bit and clean up the resources by calling a dispose method and forcing the GC to run. I save the System.totalMemory in use. After another delay I allocate some more images and after another delay I clean up again, save System.totalMemory again and check if the memory returned to the same amount (difference between them is zero).
Here is the memory usage graph I got from running the code: 
We see that the second time we clean the resources the memory returns to the same amount as the first time. This means we're cleaning everything alright.
I've put up the source code here if you want to take a look. I'm all for comments on this. I wrote to the flexunit list but haven't got any feedback.
Have you tried loading a couple of AS2 swf’s and then tried to remove them?
I have a flash site written in AS3 that need to display a bunch of banners done in AS2, but i cant seem to get the garbage collector to remove the old banners from memory when they’re done.
Hi, Really nice article. Still I am unable to find a good profiler tool for SWF files, which can be used to test the output for leakage, helping developer in optimizing their applications. While there are a lot of such tools available for VC++, Java, if we can have such profiler tool for flash, it would be really nice.
[...] Dreaming in Flash » Blog Archive » Memory Leak Unit Test – This entry was posted in Uncategorized. Bookmark the permalink. Comments are closed, but you can leave a trackback: Trackback URL. « Link Dump: 022210_1744 [...]