Game Development Reference
In-Depth Information
Garbage Collection
AS3
s garbage collection (GC) system, or the mechanism that
removes unused objects from memory, has some peculiarities
that are likely to throw off AS2 developers though they are likely
nothing new to devs from other memory-managed languages.
Ideally, a garbage collector is always keeping track of which
objects are in use and which are not, freeing up as much memory
as possible. In reality, it is not so perfect, but there are ways to
make sure your code conforms to how the GC will work. First,
it
'
s important to understand in brief how the Flash GC performs
its functions.
The AS3 GC uses two techniques to clean up your objects. The
first is known as reference counting; all the objects in memory
have a number representing how many references there are to that
object. For example, the following code creates three different
references to a single object.
'
var obj1:Object = new Object;
var obj2:Object = obj1;
var obj3:Object = obj2;
Anytime the number of references to an object changes, Flash
checks to see if that number is zero. If it is, the object is purged
from memory. In this case, as long as we set obj1, obj2, and obj3
to null , the original object will be deleted. Sounds easy and effec-
tive enough, right? Unfortunately, there are a number of scenarios
where a
object may no longer reference its child objects,
but they reference each other, as in the following example.
parent
var obj1:Object = new Object();
var obj2:Object = new Object();
obj1.otherObject = obj2;
obj2.otherObject = obj1;
obj1 = null;
obj2 = null;
'
ve nulled out the references to obj1
and obj2, they now reference each other. As a result, the garbage
collector will not purge them as it does not discriminate between
what is referencing the objects, only that something is. This brings
us to the second method the GC uses to get rid of unused objects.
It is known as mark sweeping .Inthisprocess,Flashcreatesatree
hierarchy of how all objects are connected to each other that links
back to what is essentially the root of the SWF. Any objects that are
notconnectedtothemaintreeinsomeway,eveniftheyarecon-
nected to each other, are marked for deletion from memory.
At this point, you
In this instance, while we
'
re probably thinking,
Okay, great. Sounds like
Flash has it covered.
Once again, it is not quite that simple. The
Search Nedrilad ::




Custom Search