It’s some sort of crazy nerdtastic Data Structure Deathmatch!

The Adobe Actionscript 3 Dictionary Class Vs Object Vs Array!  Man it’s awesome to have a language to work in, just like a great RPG where everyone’s got their strengths and weaknesses and it all works together to make awesome flashlove all over the web.

“What is a Dictionary Class and Why Should I read this post?”

Here’s the results from my testing right up front and I feel like it’s a good rough estimate of where each excells.

Here are some key things about these numbers.

#1: for the example code, I’m creating a new Object() and pushing it onto the array 100,000 times after assigning a cdTitle to object.cdTitle = “cdTitle_” + i;

#2: For the Dictionary, I am searching for a specific Object and right off you should notice the Search Time for the Dictionary. The example I’ll give later would be using something like a custom Enemy class… or Defense class or something resembling an object. 

With Arrays especially, and Objects to some extent, since we’ve got 100,000 objects/cds, to find one object/cd, you have to sort thru a really ridiculous amount of “not yours!” before we actually find the reference to the object/cd that we want.  The Dictionary Class actually stores an actual Object as the key.  It takes essential no time at all to search and get the correct Object because it doesn’t iterate thru each element in the Dictionary, it just jumps straight to that exact Object we need.  This is exactly the same as if we knew the exact element we needed from an Array object.

Time Benchmarks
  Array Object Dictionary
Test 1 – Create Time 0.224 ms 0.873 ms 0.286 ms
Test 1 – Search Time 0.006 ms 0.234 ms 0.000 ms
Test 1 – Remove All & End Time 0.566 ms 1.623 ms 0.988 ms
       
Test 1 – Total Memory Used 16524 19608 5328
       
Test 2 – Create Time 0.221 ms 0.864 ms 0.291 ms
Test 2 – Search Time 0.007 ms 0.239 ms 0.000 ms
Test 2 – Remove All & End Time 0.558 ms 1.621 ms 0.989 ms
       
Test 2 – Total Memory Used 16512 17380 5328
       
Test 3 – Create Time 0.089 ms 0.872 ms 0.288 ms
Test 3 – Search Time 0.038 ms 0.231 ms 0.000 ms
Test 3 – Remove All & End Time 0.127 ms 1.611 ms 0.984 ms
       
Test 3 – Total Memory Used 16512 19612 5328
       

So, here is the setup for the test.  You have a massive collection of 100,000 CDs.  You keep all of your CDs in a massive, heavy, cd case/folder/book.  However, laying in front of your Tome of All Music ( +9 ), is a single, lone CD on the floor.  It somehow fell out and we need to put it back but we don’t know where exactly in the cd case.

Let’s look at three scenarios of storing all those CDs if the cd case were AS3 code…

Arrays: Organize data by integer-indexed values, numbers… 0,1,2,3.. 100,000 ).  If you had been OCD enough and put little stickies on every cd with the exact number index of where each cd belonged in the CD case, we would not be finding ourselves in this tragic situation and we’d be golden.  …minus your severe psychological condition.  To put myCD back, we would have to have a loop, starting at either 0 and working towards cdsArr.length, or at the very end of the array…. cdsArr.length – 1 and then count down to zero looking for the correct place.  On every itteration we would need to check if the exact spot/index we were currently at was equal to the exact spot myCD said it needed to be.  You could be flipping page by page for weeks.  No good! … oh… you have an.. Ipod and all your music is in digital format?  OK Forget that.  You drop your Ipod in your morning CinnamonToastCrunch and have to go back to CDs.  Good.. back on track.

Objects: ah the atoms of Flash.  Building blocks of awesomeness.  So you remember your Ipod you allowed to skinnydip in your cereal?  You search and find songs more like how Objects let you search for them.  When you want to find a song, you simply look for the song title, or artist.  If our Magic Musical Tome stored the collection as an Object containing all of the other CD Objects, we could simply write a search function to find out where myCD.cdTitle existed in myCollection.

Dictionary!  Class!  Yay!  The AS3 Live-Doc’s for the Dictionary Class are… well… to me.. vague, unsatisfying, and didn’t help.  I’ll give a short list of links at the end for some other helpful blogs/info.

Also, the example given at LiveDocs shows how to use the Dictionary class with XML files and data, and in that scenario my brain just couldn’t put it together.  However, after enough searching and reading bits and pieces and examples, and then spending another 30 minutes trying to figure out how to Delete the objects added to the Dictionary class, the Dictionary concept finally made sense.

Let’s go ahead and make a CDCase class.  The code posted here is slightly abridged to focus on the important things.

[sourcecode lang=”php”]

package zombieflambe {
 import flash.utils.Dictionary;
 import flash.display.Sprite;
 
 public class CDCase extends Sprite {
  
   private var caseArr:Array;
   private var caseObj:Object;
   private var caseDict:Dictionary;
   private const MAX_CDS:int = 100000;
   private const MY_CD_TITLE:String = “cdTitle_90000”;
  
   public function CDCase() {
      caseArr  = new Array();
      caseObj  = new Object();

      /**********************************
       * public function Dictionary(weakKeys:Boolean = false)
       * weakKeys:Boolean (default = false) — Instructs the Dictionary object to use “weak” references
       *   on object keys. If the only reference to an object is in the specified Dictionary object,
       *   the key is eligible for garbage collection and is removed from the table when the object
       *   is collected.
       *****************************/
      caseDict = new Dictionary( true );
   
      var myCD = new Object();
      myCD.cdTitle = MY_CD_TITLE;
   
      // Initialize all our cases
      var i:int = 0;
      for( i ; i < MAX_CDS; i++ )        {          var tmpCD:Object = new Object();          tmpCD.cdTitle = "cdTitle_" + i;              caseArr.push( tmpCD );              // Objects need a string-based index         caseObj[ tmpCD.cdTitle ] = tmpCD;              // The "key" is the actual object.. our CD         //   the 'value' is a string that's just the cd's title.         caseDict[ tmpCD ] = tmpCD.cdTitle;              // This lets us hold onto the reference of the tmp cd         if( tmpCD.cdTitle == myCD.cdTitle )             myCD = tmpCD;       }              var result1:int           = searchArray( myCD );       var result2:int           = searchObject( myCD );       var result3:Boolean   = searchDictionary( myCD );       trace( "Result1: " + result1 );       trace( "Result2: " + result2 );       trace( "Result3: " + result3 );           clean();    }       private function searchArray( myCD:Object ):int  {       var i:int =  0; //MAX_CDS - 1;       var titleFoundAt:int = -1;       for( i; i < MAX_CDS; i++ )        {          if( caseArr[ i ] == myCD )           {              titleFoundAt = i;              break;          }      }      return titleFoundAt;    }       private function searchObject( myCD:Object ):int  {       var i:int = MAX_CDS - 1;       var titleFoundAt:int = -1;             for( i; i >= 0; i– ) 
      {
         if( caseObj[ “cdTitle_” + i  ] == myCD ) 
         {
            titleFoundAt = i;
            break;
         }
      }
      return titleFoundAt;
  }
  
   private function searchDictionary( myCD:Object ):Boolean  {
      var titleFound:Boolean = false;

      // Checking to see if myCD Object exists in the Dict
      if( caseDict[ myCD ] )
         titleFound = true;
   
      return titleFound;
   }

 }
}

[/sourcecode]

Sourcefiles, FLA, SWF, AS
Download ZF_CDCase_Array_Object_Dictionary_Test.zip

Dictionary Class Links for Further Reading:
( 2/4/09 Update: added 3 more Dictionary Reference links )

Categories:

4 Comments

Leave a Reply

Avatar placeholder