Below code demonstrates the memory usage by the Dictionary when using strong reference v.s. weak references :
var dict:Dictionary = new Dictionary(true/false);
for(var i:int = 0; i < 999999999; i++) {
dict[new Application()] = 1;
if(i % 1000 == 0) {
trace(i + " - memory: " + System.totalMemory);
}
}
and the result:
No. of cycles | Memory usage in Mega bytes Dictionary - strong reference | Memory usage in Mega bytes Dictionary - weak reference |
4000 | 24.2 | 12.3 |
8000 | 38.3 | 11.7 |
12000 | 51.8 | 11.3 |
16000 | 66.2 | 14.0 |
20000 | 79.5 | 13.6 |
Clearly, when you use weak reference with Dictionary, it dances perfectly with the garbage collector. You can use Dictionary to implement your own weak referenced cache. Beware though, Dictionary can only be configured with keys weak referenced, which may look awkward when you use it this way. My suggestion is that you wrap the functions in a class.