Till Schneidereit

Partly, yes

Dictionaries in AS3: A tale of awesomeness and restrictions

| Comments

Update: @stray_and_ruby kindly made me aware of the fact that it isn’t entirely obvious what this post is about. I’m talking about a fairly obscure, but really handy usage of the Dictionary class: Implementing weak references to objects.
@sunjammer recently posted about the Dictionary class in AS3. I agree with him: Dictionaries are awesome.

Unfortunately, they’re only nearly as great as he describes them because of one little snag: Weak Dictionaries are only “weakly keyed”, not “weakly valued”, meaning that assigning an object as a value creates a strong reference to that object - even if that very same object is also used as the key for the entry.

That’s especially unfortunate because it doesn’t allow for efficiently implementing weak references with low overhead:

Instead of using something like

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
package
{
  import flash.utils.Dictionary;
  public class WeakReference
  {
    private static const _referencesHolder : Dictionary = new Dictionary(true);
    private static var _nextReferenceID : int = 0;
    private const _referenceID : int = _nextReferenceID++;
    public function WeakReference(target : *)
    {
      _referencesHolder[_referenceID] = target;
    }
    public function get target() : *
    {
      return _referencesHolder[_referenceID];
    }
  }
}

you have to use something with much more overhead:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
package
{
  import flash.utils.Dictionary;
  public class WeakReference
  {
    private const _referenceHolder : Dictionary = new Dictionary(true);
    public function WeakReference(target : *)
    {
      _referenceHolder[target] = true; //every basic type works as the value
    }
    public function get target() : *
    {
      for (var value : * in _referenceHolder) return value;
      return null;
    }
  }
}

On another note, I naturally had to google “awesomeness” and what do you think ensued? Correct: Awesomeness! Specifically, the result contained, besides lots of links to Barney Stinson and HIMYM in general, this fantastic service. I mean seriously: Who doesn’t like to be reminded of being awesome? And if you ask me, $45 a month is dirt cheap for that happening reliably and on a daily basis. (Just as the providers of the service, I’m only half-joking, btw. I’m sure there are lots of people out there whose life can be improved by such a service.)

Comments