Object Graphs, the GC, and System.disposeXML()

AIR 1.5.2 contains a new, performance-related API that heavy users of XML may find handy, System.disposeXML(), that is an instructive example regarding use (and abuse) of the AIR garbage collector.

When an XML document is loaded, it’s stored in memory as a graph of individual objects representing elements, text, attributes, and so on. Each pair of related objects–for example, a parent/child element parent–are linked, in the underlying representation, with pointers going in both directions.

This is a convenient representation for traversal, but can be problematic for the garbage collector. As I mentioned in my earlier post about referencing counting and ActionScript objects, the garbage collector will eventually find and discard the entire set of objects after the last external reference is removed. However, it takes more work for the GC than less-connected data structures.

In practice, the amount of time it takes the garbage collector to do its job is related both to the number of allocated objects and the number of pointers between them. So while it is nice that the GC is capable of finding even these highly-connected graphs of objects, using them is also asking it do a lot of work. You can reduce this workload by explicitly disconnecting the pointers between objects.

For graphs of ActionScript objects, you can ease the GC workload by simply nulling out reference between the objects. Note that you don’t have to find every last reference for this to be helpful. The GC will still do it’s job in the end, and every bit of clearing references helps. For ActionScript objects this can be particularly helpful because, if their reference count then goes to zero, they can be cleaned up even before the GC sweep completes.

XML objects are a trickier case because the API doesn’t allow developers to traverse the actual object graph. That’s where System.disposeXML() comes in: It traverses the internal object graph backing the XML object, setting all of the internal points to null. Afterwords, the XML object is empty and, presumably, useless. But then, since you were done with it anyway, that shouldn’t be a problem.