Memory
Let’s say it one more time: the memory on mobile devices is limited. If you exceed it, Android will terminate your application.
Creating Objects
Choose the appropriate object. For instance, use a Sprite
instead of a MovieClip
if you don’t need multiple frames.
Use a Vector
, which is more
efficient than an Array
, to store
objects. Call the getSize()
function to determine the memory footprint for a particular data
type.
Allocating new blocks of memory is costly. Create your objects at an idle time, ideally when your application first initializes, and reuse them throughout your application.
Object pooling creates a pool to store objects and re-use them over time. In this example, we pop an object, or create one if none exists, and then push it back when done until the next use:
import flash.display.Sprite; var pool:Vector.<Sprite>(); // get a new Sprite var sprite:Sprite = popSprite(); sprite.init(); // set properties as needed addChild(sprite); function popSprite():Sprite { var sprite:Sprite; if (pool.length > 0) { sprite = pool.pop(); } else { sprite = new Sprite(); } return sprite; }
When the object is no longer needed, return it:
removeChild(sprite); pushSprite(sprite); function pushSprite(sprite:Sprite):void { pool.push(sprite); }
This approach is organic. The application creates objects as needed until it reaches a sufficient quantity to recycle them. Another method is to create all the objects initially, up to a maximum amount.
Removing Objects
Memory is dynamic. As objects are ...
Get Developing Android Applications with Adobe AIR now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.