Search code examples
javaandroidlibgdx

Java LibGDX Confused About Memory Usage


Hello should I do like this:

new BitmapFont().draw("Hello World!");
new BitmapFont().draw("Hello Universe!");

or

BitmapFont font = new BitmapFont();
font.draw("Hello World!");
font.draw("Hello Universe!");

Does it matter for performance?


Solution

  • The first option isn't only worse, it is not an option at all. It leaks memory. If you're doing this every frame, your game will crash pretty quickly on a phone.

    Anything that implements Disposable absolutely must be disposed before you lose the reference, or it leaks.

    The second option is fine for most cases. If you have dozens of strings that have the same text on every frame, you can use BitmapFontCaches that you create from your BitmapFont (someStringCache = new BitmapFontCache(bitmapFont);) so the glyph arrangement for the string doesn't have to be recalculated every time you draw it. I wouldn't bother with this unless you find that your game's framerate is too low and you've narrowed the problem down to CPU.