Search code examples
javaperformancelibgdxscene2d

Performance in constants referencing - LIBGDX


I have got a lot of conditional if´s and switches in order to check and compare positions. there are probably thousands of references to constants in each frame render :

if(sprite.getY>10.2f) accel+=2f;

Leaving asside the readability, would thousands of lines like the one bellow be faster than thousands of lines like the upper one?

public static final float MINYPOS = 10.2f;
public static final float ACCELY = 2f;
.....
if(sprite.getY>MINYPOS) accel+=ACCELY;

Solution

  • Any reasonable Java compiler will inline constants (see is it possible to disable javac's inlining of static final variables?, which is asking about how to stop it from happening).

    Generally, though, you want to optimize based on measured performance problems. Start by building code that you know works (since that's the hard part). Once it works you can use tools to measure it and decide if it needs to be optimized (often it won't).