AIR 3 has a new API to allow developers to provide the runtime’s garbage collector with hints. The API is called
System.pauseForGCIfCollectionImminent(), and it requires a little explanation to understand both it’s utility and value.
Before I get into how the function works, let’s start with why you’d want to give the garbage collector pointers (no pun intended) to help it decide when to reclaim memory. Running the garbage collector can cause the runtime to pause, and while the pause is typically imperceptible, if you’re doing something like playing a fast-paced game, you might notice it. In this particular scenario, a better time to garbage collect might be between game levels. Or, if you’re building something like an e-reader, it would be best to reclaim memory while the user is reading as opposed to during your super slick and smooth page-flip animation.
System.gc() function can force the runtime to garbage collect, however it doesn’t always have 100% predictable results across all platforms, and forcing garbage collection on a regular basis is usually overkill.
System.pauseForGCIfCollectionImminent(), on the other hand, does not force garbage collection, but rather serves as a mechanism to tell the runtime that a particular place in your application would be a good place to reclaim memory, and to specify how likely it is that runtime will take that advice. The function takes a single parameter called
imminence which is a
Number indicating the strength of your recommendation. From the spec:
The GC will synchronously finish the current collection cycle (complete the marking and perform finalization) if the current allocation budget has been exhausted by a fraction greater than the fraction indicated by the parameter
If it’s still not entirely clear, here are some examples:
|Imminence||Meaning / Result||Likelihood|
|.25||If more than 25% of the allocation budget has been used, finish the current collection cycle.||More likely|
|.75||If more than 75% of the allocation budget has been used, finish the current collection cycle.||Less likely|
In the former case, you’re essentially saying, "I really want you to garbage collect right now because a lot of animation is about to happen which I want to be as smooth as possible," and the latter case is essentially saying, "If you were going to garbage collect pretty soon anyway, now would be a pretty good time."
If you’re currently using
System.gc() to force garbage collection in your AIR applications, I highly recommend you take a look at this new API.