Reputation: 75
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?
Upvotes: 0
Views: 125
Reputation: 93922
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.
Upvotes: 2
Reputation: 9048
Definitely second option is better, because the first one creates 2 objects when 1 is really needed. On small scale this does not matter, but if all Java calls were made like the first one, garbage collector would take much more time (more objects - more time GC needs) and if there was a heavy load on constuctor it would significantly slow an application.
Object are in memory so the more objects you have the more memory is needed, that is why libGDX want to reuse the same Batch object everytime it is practical.
It is also less readable and configurable (if you need to set something in BitmapFont it is better to do it once).
You should also check for objects that implements Disposable
, you have to dispose them manually fe. BitmapFont, Batch, Stage, Texture.
Upvotes: 1