Faster Garbage Collection With Corona

Before Tilt Monster was released, I was browsing around the Corona developer forums and came across a thread titled, Garbage Collect Delay?

A Corona developer, tempop, said he noticed a pretty significant delay when calling the Lua function, collectgarbage( “collect” ), but the delay isn’t present when adding that call to a timer delay, even if the delay is only for a single millisecond, which ultimately results in faster memory freeing.

I never knew there was a delay, so my interest was definitely peaked. The developer said that they ran tests to confirm that the delay was in-fact present, and that the delay was absent when added to a timer.

I decided to replace any garbage collection lines in Tilt Monster with:

timer.performWithDelay(1, function() collectgarbage("collect") end)

And it did in fact result in overall better performance!

I’ve also experienced ZERO game crashes since I added that line, so I’m very thankful to have read that thread.

Before the “hack”, I had optimized my code to the point I felt I could really go no further, but was still experiencing crashes every once in a blue moon (due to memory warnings). The crashes no longer occur since replacing the garbage collection lines with timer-delayed ones.

Looking back, I guess the crashes were a result of the garbage collection delay. Most likely, a few calls to “collectgarbage()” were probably called before any were able to actually execute (because of the delay) and I assume that’s what caused memory problems to occur.

I think this kind of instant garbage collection is absolutely essential for arcade-style games where you need to load and unload objects quickly between rounds, and where rounds can begin/end in a matter of seconds.

The whole thing above sounds kind of like a bug to me, but at least for the time being, the 1 millisecond delay should fix garbage collection delay problems. So special thanks to tempop for the awesome catch!

To read more entries, visit the archives or subscribe to the RSS feed.