October 28, 2011

Memory leaks in AS3

A short comment on memory leaks in AS3. In many cases, memory leaks are no problems in AS3, since most Flash content is not very complex and swf files are often reloaded (e.g. if they are only part of an html page, such as a banner). In some cases, such as when you create a Flash application or when an entire site is built in Flash or Flex, then memory leaks could build up to very high levels.

In order to monitor memory usage you can call System.totalMemory:

trace(System.totalMemory);

The most common reason why memory leaks occur is that we add event listeners with strong references to objects, which prevents those objects from being garbage collected. As a best practice to prevent this, you should always use weak references when creating event listeners:

label.addEventListener(MouseEvent.Click, handleMouseClick, false, 0, true);
instead of

label.addEventListener(MouseEvent.Click, handleMouseClick);
Grant Skinner discusses the importance of weak references and resource management in more detail on his blog.

No comments:

Post a Comment