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.
本文通过实验对比了在ActionScript中使用强引用与弱引用Dictionary对内存的影响。结果显示,使用弱引用能显著减少内存占用,并有助于垃圾回收。建议在实现缓存时采用弱引用以优化应用性能。
2491

被折叠的 条评论
为什么被折叠?



