Lua Garbage Collection Tip

By default, Lua handles garbage collection automatically—meaning, in most cases, you don’t have to think about it (in case you didn’t know, garbage collection is the act of freeing up memory on unused resources, e.g. variables that have been set to nil).

However, there are cases where you might not want Lua to perform a garbage collection cycle, such as intense gameplay moments when you have multiple objects moving about the screen, where any slight hiccup could affect the user’s gameplay experience.

For example, in my game Tilt Monster, the gameplay is pretty fast-paced. The screen scrolls quickly for the duration of each round while the player tilts the device to avoid collisions, and any slight bit of lag could cause an adverse affect on the player’s experience. To prevent that (as much as possible), I’d want to do anything and everything I could to make sure performance takes first priority.

I’m not exactly sure how much “energy” it takes for Lua to perform a garbage collection cycle, but since rounds are relatively short in Tilt Monster to where I know uncollected “junk” isn’t going to pile up for the duration of a game, I’d rather Lua not perform a garbage collection cycle during gameplay.

Therefore, I would simply stop the garbage collector like so:

collectgarbage( "stop" )

Then, once the round is over and there is a break in gameplay (e.g. the “Game Over” screen), then I would allow the garbage collector to resume normal activity, and force a collection cycle as well:

collectgarbage( "restart" )
collectgarbage( "collect" )

Of course, I’d call that after removing and nil’ing out the objects from the previous round.

Like I said, I’m not sure how much “juice” a Lua garbage collection cycle sucks up, but since it’s just one line of code to prevent it from happening, it’s worth it for whatever performance it could potentially bring your app when you are in need of every ounce of “horsepower” for a specific portion of your app’s runtime.

Note: Do not—I say again—do not forget to restart the garbage collector at some point though! If you do forget, your app could crash from having too many objects just sitting in memory that need to be cleaned up.

HostGator $3.96

$3.96 for web hosting – used by Get started today.