The last item that we'll examine is the Loader class (also apply to URLLoader). In actual fact, this examination doesn't have any real application, it's just something that might confuse some people so I want to address it.

Frame 6 code:

var request:URLRequest = new URLRequest("images.jpeg");

var countDic:Dictionary = new Dictionary(true);

addEventListener(Event.ENTER_FRAME, enterFrameLoader);

function enterFrameLoader(aEvent:Event):void
{
    try {
        var loader:URLLoader = new URLLoader();
        loader.load(request);
        countDic[loader] = 1;
    } catch (error:Error) {
        trace("Unable to load requested document.");
    }
 
    var n:int = 0;
    for (var key:* in countDic) {
        n++;
    }
    mTxtInstanceCount.text = "Number of keys " + n;
}



The code is nothing fancy. All it does is adding a new Loader object that loads an image on every frame and count the number of Loader objects in memory. Recall that earlier in this article, it has been shown that if we constantly add arrays to a weak reference dictionary, the number of objects stays at 1. As you might have deduced from previous tests on movie clips, Loader objects don't get garbage collected immediately.

Now run GCExample.fla on Flash IDE and click on "Test Loader", you'll find the number of keys increase indefinitely. To dramatize this a little bit more, you can try adding the LocalConnection hack to the end of the frame handler function.

...
     var n:int = 0;
     for (var key:* in countDic) {
        n++;
     }
     mTxtInstanceCount.text = "Number of keys " + n;

     try {
         new LocalConnection().connect("foo");
         new LocalConnection().connect("foo");
     } catch (e:*) {}
}


Strangely enough, even the outrageous code that force GC on every frame does not make the Loader objects go away at all. Rest assured, this is something that only occurs on the standalone Flash Player. If you run our example on a browser, for instance Firefox, the instance count remains at 2 or 3. And if you remove the LocalConnection hack, it may go up to over 100 before dropping back to 0. Apparently, this is only an interesting phenomenon to observe, not anything serious that needs to be taken care of.

That concludes this article. I hope it help answer/clarify questions/thoughts someone might have, as I did. I know I didn't write best code so please feel free to point out where it should be improved/corrected.