写了很多时间的Flex程序,感觉Flex/AS在内存和性能方面的设计有一定的局限。我把对这两方面的一些经验记录在此,希望能抛砖引玉。
- 及时移除无效的事件监听器(event listeners),以避免造成内存泄漏。
- 及时卸载Loaders
当你使用Loader加载对象时,当该对象无用之后,及时调用unloadAndStop()卸载该对象,然后使用垃圾回收器(gc)回收Loader。AS3中的GC可能需要重复调用两次才能生效。特别针对静态图像文件使用这个技术可以有效地避免内存膨胀。 - 在你自建的类中,设立dispose()方法 –> 参见 DOJO toolkit 的 widget 组建的模板方法。
- 调用集合对象的disableAutoUpdate()/enableAutoUpdate() 方法,以避免在批量修改集合中对象时,造成大量无用的冗余事件。
- 在自建组件时,通过重载createChildren()方法来延迟子对象创建,而不要把所有的子对象的创建全部放在自建组件的构造方法中。
- 对象的创建是一个高资源消耗操作,因此尽量使用 ObjectPool 来复用对象。
- 在 invalidate/destroy/re-validate 你的组件之前,做一个lazy checking,以避免无谓的运算开销
- 善用常数,常数的访问速度快。常数都设成静态属性。
- 将工具方法以及其他各种无状态的方法写成静态方法。静态方法附属于类,因此无需对象初始化就可以使用,减少内存占用。
- 对于应用程序级别的事件,可以采用GlobalObject 或者 静态EventDispatcher 来做事件中转。这样设计的代价是增加了程序和这个程序级对象之间的紧偶尔,但是好处是大大降低了事件处理所需要的计算机资源。
- 使用green-threads来减缓大运算量逻辑对播放头的帧计算的压力。
参考阅读
- 10 Tips for Flex Application Performance
http://www.insideria.com/2009/09/10-tips-for-flex-application-p.html - Good Memory Management When Using PureMVC
http://jessewarden.com/2009/11/good-memory-management-when-using-puremvc.html - Unloading Flex Modules
- Resource Management in AS3 Session Notes Available
- AS3 Resource Management: Part 1
- Garbage Collector Interactive Simulator
- Garbage Collection and Memory Leaks
- Memory Performance in the Land of References
- Flash Player Memory Management
- Using Object Pools
- Object Pool Class
- Tweening and Object Pools
- Garbage Collection with Flex and Adobe AIR
- Screencast: Performance and Memory Management
Post a Comment
You must be logged in to post a comment.