What are good memory management techniques in Flash/as3

十年热恋 提交于 2019-12-04 12:08:07

Flash bytecode is run by the AVM (Actionscript Virtual Machine). In general terms (and without being an expert in Java or the internals of the Flash Player), I think it's safe to say that the AVM model is somewhat analogue to the JVM model (source code is compiled to bytecode, which is run by the VM; in AVM, at least, some of it is interpreted and some is JIT compiled to native code before execution, etc).

AVM is, as you said, garbage collected, so basically memory allocation and deallocation is managed for you by the GC. When an object becomes unreachable, it's eligible for GC (which doesn't mean it is collected right away).

There's a way to force a GC cycle, only available in the debug version of the player, and also a hack, unofficial and undocumented, but you can find some links about it in google (try GC hack flash LocalConnection or something along those lines). Forcing a GC is almost always a bad idea though.

I've recently come across this blog post that explains how the GC works in some deatil, with references to the AVM C++ source code (that part of the player is open source, so you can check it out for more in depth info if you're so inclined). http://jpauclair.net/2009/12/23/tamarin-part-iii-current-garbage-collector-in-flash-10-0/

On a very specific note: memory leaks can become rampant in your code when using EventListeners. The most common example I've seen in AS/Flex tutorials for adding listeners looks like this:

button.addEventListener(MouseEvent.CLICK, doSomething);

This works just fine, but ignores one salient point: the listener is strongly referenced. This means when the component containing this button is GC'd, the listener persists and maintains a reference to the button, meaning it also won't be harvested.

To mitigate this, you can do one of two things:

button.addEventListener(MouseEvent.CLICK, doSomething, false, 0, true);

Here is Adobe's description of the 3 extra fields. Note what they say about strong references:

A strong reference (the default) prevents your listener from being garbage-collected. A weak reference does not.

The other option is to create a destructor in your code so when a component which uses EventListeners removes them before being torn down:

button.removeEventListener(MouseEvent.CLICK, doSomething);

In addition to what has already been answered it is good idea to use a library like Mr Doob's Actionscript Performance Monitor which will activley display the current memory usuage. Useful for detecting and fixing memory leaks.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!