Sunday, November 6, 2011

Programming Challenges: Garbage Collection

Flash (and many other programming languages) have a wonderful feature that makes program development easier to get into. Flash has a Garbage Collector that runs automatically when the program's memory reaches its limit. Basically, the Garbage Collector (GC) checks all the objects to see if they're connected to anything. Anything with 0 connections gets deleted and the memory it took becomes available for use again. Next, the GC checks every connection from the root of the program and marks everything that's still connected to root. Anything not connected back along some line can't be accessed ever again by the program, and is also deleted, even if it has links to other objects.

In order for the garbage collector to be effective, any objects your program isn't going to need ever again need to be disconnected from everything. Objects with 0 links are much faster for the GC to find and remove than groups of interconnected objects that are inaccessible to the program.

A good way to imagine this is a cork-board with a bunch of pins, and strings linking one pin to another. Each pin is an object. Each string connecting one pin to another is a link. The Garbage Collector comes along when your board is too full of pins to put any new ones in.

As you do things on your cork-board, you want to cut all the strings connected to a pin you're done with, because that's the easiest and fastest way for the GC to know it needs to be pulled out.

Another way to manage memory (and it's more memory-efficient than good garbage collection practices) is to recycle objects when you're done with them. That is, change the values of an object you're done with to match the new object of the same type you want to create.

You could have an array of objects you re-use often, and whenever you would want to make a new one, it first sees if there's anything in your recycle array. If there is, it assigns the new values to the existing object and assigns that object to the needed reference. If there is nothing in the recycle array, then it creates a new object. Whenever you're done with an object, you add it to the recycle array and then cut all other references to it.

If you do this, you'll want a function in each recycled object's class that resets its variables, with the same inputs as the constructor. In fact, it will usually mirror your constructor.

No comments:

Post a Comment