缓存与垃圾收集 GC and Cache

HEINS TRASH FULL One of the performance tips is recycling whatever you created as long as the memory allows. In Java, it's pretty easy to implement a cache using weak references. In AS, it's easy too. You just use Dictionary.

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. 

A good article on GC and FVM: Understanding Memory Leaks in ActionScript