Sunday, March 31, 2013

Garbage Collector is garbage

Whenever you are playing around with OpenGL and LWJGL in Java, say LibGDX, Slick2D or pure LWJGL, please keep this in mind: Java Garbage Collector is NOT your friend. There are a few reasons that make it suck for games. One of them is 'the moment' it chooses to start working. If Java garbage collector is messing around during our main loop, it may cause it to take longer to complete each cycle, causing our game to lose FPS.

There's another reason to hate Java garbage collector: it doesn't work with video RAM. Whenever you load a texture on LWJGL or any LWJGL-based library, actual image data is loaded as a pixmap on video RAM. OpenGL stores graphical data on video RAM so that your graphics card can access faster to it.

However, video RAM is not the VM heap. That means that Java Garbage Collector won't free your textures -you must do that manually, by using the appropiate method depending on the platform you are using, dispose() or destroy(). If you don't release your textures, you will end with memory leaks and your will require a lot of memory: this might not be a problem at all on desktop platforms, but if you are planning to release a mobile phone game, you should be aware of this.

Remember to destroy your textures once you aren't using them. Doing some image = null is not enough: as I said, that won't remove your pixmap data on video RAM. Plus, if you remove all the references to your texture, it's over: you won't be able to destroy the pixmap and that memory bank used by your pixmap becomes lost and wasted until you close the game.

Aside note: make sure to destroy textures that you aren't using. Sometimes pixmaps get shared across multiple texture or image objects. Consider the following example in Slick2D: you load an Image, then you create a SpriteSheet, and then you use an Image array to reference three sprites. You are using five objects here, your original image, your spritesheet and three references to some subimages of your original image. However, they all will be sharing the same pixmap on video RAM. If you destroy that pixmap, you destroy the pixmap for all of them. So, if you are using a spritesheet, a tileset, a bitmap/AngelCode font, be careful on deleting pixmaps.

No comments:

Post a Comment