缓存与垃圾收集 GC and Cache

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

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

 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 cyclesMemory usage in Mega bytes
Dictionary - strong reference
Memory usage in Mega bytes
Dictionary - weak reference
400024.212.3
800038.311.7
1200051.811.3
1600066.214.0
2000079.513.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. 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值