Java – ‘static’ and ‘non-static’ fields get better performance in Java Android

‘static’ and ‘non-static’ fields get better performance in Java Android… here is a solution to the problem.

‘static’ and ‘non-static’ fields get better performance in Java Android

I develop games using openGL 2D on Android.

Because my View is complex and contains 300-400 objects at the same time (game loop), it’s hard to get a performance level.

I know static and non-static fields in Java very well:

private final static int NUMBER = 10;


private final int NUMBER = 10;

My problem is not encapsulation (as OO) but performance.

Which is better for performance, static or non-static fields.

My idea is that for most of my logic, I use primitives like float/int.

I created a generic parent class (super class) for all my “views”, which must be more efficient within the performance range:

Examples are as follows:

    /** Sprite sheet definition */
private final int SPRITE_WIDTH = 4;
private final int SPRITE_HEIGHT = 4;

private float mScreenWidth, mScreenHeight, wRatio, hRatio;
private int mFrame = 0;
private int mSwitcher = 0;
private final int TEXTURE_COUNT = 1;  for sprite sheet we use 1 image all the time.
private int[] textures = new int[TEXTURE_COUNT];  frame animation

protected FloatBuffer vertexBuffer;

private final ESpriteDirection mDirection = ESpriteDirection.TOP_TO_DOWN_LEFT_TO_RIGHT;

public float x, y, initPos, finalPos, initSpeed, currentPos;

private ByteBuffer bb1;


private FloatBuffer[] floatBufferArray = new FloatBuffer[TOTAL_IMAGE_COUNT_IN_SPRITE];

private float xOffset = 1.0f/SPRITE_WIDTH;
private float yOffset = 1.0f/SPRITE_HEIGHT;

private float vertices[] = {            

private float storage[][] = new float[TOTAL_IMAGE_COUNT_IN_SPRITE][];
private int[] sprite_X_Indexes = new int[SPRITE_WIDTH];//{1,2,3,4}; 
private int[] sprite_Y_Indexes = new int[SPRITE_WIDTH];//{1,2,3,4};

I can guess that the static field is better for multiple launches of the same class, eh



From a performance POV perspective, once your code is compiled, it should make little difference because both your static and (single) non-static fields have been converted to memory locations.

Declaring a field as static may provide some optimization possibilities at the compiler level. On the other hand, static objects may not typically “approach” the instance data in memory, which is detrimental to cache performance.

In general, this is not where you should spend your time until/unless you have exhausted all the algorithm optimizations, and then only after you know that this is actually where you waste your time.

Related Problems and Solutions