Am I Completely Insane Or What

Another ActionScript-related memory-usage post. I’ve been doing some experiments with flash.display.Loader (a class which has always seemed out to get me). Today I discovered something which is just so weird it makes me doubt my own sanity. I’d be grateful if any Flash/Tamarin experts out there could help me verify my sanity/insanity.

Here is the test script I’ve been running:

public static const NUM_LOADERS:int = 500;

public function TestMultipleLoaders()
{
init();
}

private function init():void
{
for (var i:int=0; i < NUM_LOADERS; i++)
{
createAndDestroyLoader();
}
}

private function createAndDestroyLoader():void
{
var loader:Loader = new Loader();
loader = null;
}
}

Compile this in Flash Builder and test it under the Profiler. Change the filter to include objects in the flash.* package. Observe how many Loader instances are in memory. Hit the garbage collector. Observe again.

If your system is running anything like mine, you will see 500. Which, in itself, is crazy. loader is just a local variable which, anyway, is set to null. But bear with me, this is going to get crazier…

Now try playing with the value of NUM_LOADERS. Again all things being equal, you will see this crazy behaviours (NUM_LOADERS Loaders persisting in memory) for any number between 1 and about 600. Somewhere around that figure, perhaps a little higher (it doesn’t seem to be predictable) you will see the number of Loaders persisting drop to either 1 or 0.

Now what the hell is going on here? My guess is that the Loader class is somewhat resource-intensive to create, and so Adobe are maintaining a pool of them somewhere, although the strategy for doing it seems a bit random.

Please can somebody, anybody, enlighten me?