How can I avoid garbage collection delays in Java games? (Best Practices) [closed]

I’ve worked on Java mobile games… The best way to avoid GC’ing objects (which in turn shall trigger the GC at one point or another and shall kill your game’s perfs) is simply to avoid creating them in your main game loop in the first place.

There’s no “clean” way to deal with this and I’ll first give an example…

Typically you have, say, 4 balls on screen at (50,25), (70,32), (16,18), (98,73). Well, here’s your abstraction (simplified for the sake of this example):

n = 4;
int[] { 50, 25, 70, 32, 16, 18, 98, 73 }

You “pop” the 2nd ball which disappears, your int[] becomes:

n = 3
int[] { 50, 25, 98, 73, 16, 18, 98, 73 }

(notice how we don’t even care about “cleaning” the 4th ball (98,73), we simply keep track of the number of balls we have left).

Manual tracking of objects, sadly. This how it’s done on most current well-performing Java games that are out on mobile devices.

Now for strings, here’s what I’d do:

  • at game initialization, predraw using drawText(…) only once the numbers 0 to 9 that you save in a BufferedImage[10] array.
  • at game initialization, predraw once “Your score is: “
  • if the “Your score is: “ really needs to be redrawn (because, say, it’s transparent), then redraw it from your pre-stored BufferedImage
  • loop to compute the digits of the score and add, after the “Your score is: “, every digit manually one by one (by copying each the time the corresponding digit (0 to 9) from your BufferedImage[10] where you pre-stored them.

This gives you best of both world: you get the reuse the drawtext(…) font and you created exactly zero objects during your main loop (because you also dodged the call to drawtext(…) which itself may very well be crappily generating, well, needless crap).

Another “benefit” of this “zero object creation draw score” is that careful image caching and reuse for the fonts is not really “manual object allocation/deallocation”, it’s really just careful caching.

It’s not “clean”, it’s not “good practice” but that’s how it’s done in top-notch mobile games (like, say, Uniwar).

And it’s fast. Darn fast. Faster than anything involving the creation of object.

P.S: Actually if you carefully look at a few mobile games, you’ll notice that often fonts are actually not system/Java fonts but pixel-perfect fonts made specifically for each game (here I just gave you an example of how to cache system/Java font but obviously you could also cache/reuse a pixel-perfect/bitmapped font).

Leave a Comment