Friday, October 8, 2010

AS-3/Flex Dictionary weak keys


A sample source code for using a dictionary in AS-3/Flex with weak keys.
When I say new Dictionary(true), after a while all those objects, whose
only references are as the dictionary keys, will be garbage collected.
So, if run the following in debug mode, after a while, output of trace 
will be 0, from 1 initially. 

   1:  <?xml version="1.0"?>
   2:  <mx:Application xmlns:mx="http://www.adobe.com/2006/mxml" creationComplete="init()">
   3:      <mx:Script><![CDATA[
   4:          private var di:Dictionary = new Dictionary(true);
   5:          private function init():void {
   6:             di[new Sprite()] = [1,2,3];
   7:              setTimeout(startTrack,5000);
   8:          }
   9:   
  10:          private function startTrack():void {
  11:             System.gc();
  12:              var count:int = 0;
  13:              for each (var arr:Array in di) {
  14:                  ++count;
  15:              }
  16:              trace("number of elements in dictionary = " +count);
  17:              setTimeout(startTrack,5000);
  18:          }
  19:          ]]></mx:Script>
  20:  </mx:Application>

No comments:

Blog Archive