为了保障原创作者在本站发表文章的利益, 并维护本站原创的精神, 特声明: RIAShanghai对有以下任何情况之一的文章将不通知作者并直接进行快意删除:
- 非原创, 或者原创但一文多发;
- 各种形式的广告与吹擂;
- 不符合本站文章格式.
欢迎各位读者监督. 谢谢合作. 另: 作为Adobe正式的UG, 我们将把Adobe不定期分发的软件,书籍及各种纪念品赠送给发文活跃的作者, 共同进步.
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