Warning: array_key_exists() [function.array-key-exists]: The second argument should be either an array or an object in /nfs/c02/h11/mnt/28735/domains/www.doomsday.no/html/esn/wp-content/plugins/g-crossposting/gplus-crosspost.php on line 126
Electronic Space Nintendo Rotating Header Image

Using the AS3 Dictionary utility

Edit: As some comments point out, I’ve misunderstood the exact nature of a weak dictionary, and I’ve updated the post accordingly. Thanks readers! :-)

Just a quick post to point out how freaking sweet the AS3 Dictionary utility is. They have rapidly become my favorite data structure for the simple reason that they allow you to create a fast hash map of sorts of any key/value set in a way that lets you integrate more elegantly with garbage collection.

//oldskool hash table entry
var map:Object = {};
var hash:String = myHashableObject.getHash();
map[hash] = myHashableObject;

The glory of hash tables of course is O(1) lookup speed; The ability to see if an object has been stored and to retrieve it without first iterating over the collection or doing some other search.

The wonderful thing about Dictionaries is how they simplify this process. You don’t need a hashing function anymore: To collect a set of objects, all you really need to do is use the same object for both key and value:

//super illin'
var map:Dictionary = new Dictionary();
map[myObject] = myObject;

This nets you the O(1) lookup, collection iteration through for..each and for..in, and the sexy, sexy ability to declare the Dictionary “weak”, meaning it won’t stop its key from being garbage collected.

Weak dictionaries are a cornerstone of the DConsole for performance, and to make sure inspecting an object wouldn’t create a strong reference to it. They are also used throughout the autocomplete solution in the form of ternary trees.

Dictionaries let you approach object collections of any time with ease and elegance. I strongly recommend you play around with them if you haven’t already.

Look out for an upcoming post detailing the Notification framework used by Doomsday Console 64, as it offers an excellent use case.

2 Comments

  1. [...] recently posted about the Dictionary class in AS3. I agree with him: Dictionaries are [...]

  2. Roland Zwaga says:

    “meaning it won’t stop its value or key from being garbage collected.”

    This is not true, only the KEY has a weak reference, the VALUE has a strong reference, please be aware of this.

    cheers,

    Roland

Leave a Reply