javamemoryheap-memorylarge-object-heap

Java Memory Allocation of large object sets


I'm currently working on a game engine in java, however I'm having preformance issues when allocating large sets of objects on the heap, for example

public class GLParticleSystem { 

  private GLParticle[] particles = new GLParticle[2000];
  private int numberOfParticles;

  public GLParticleSystem(numberOfParticles) {
     this.numberOfParticles = numberOfParticles;
  }

  public void init() {
    for (int i = 0; i < numberOfParticles; i++) {
        particles[i] = new GLParticle();
    }
  }

}

The above piece of code will suffer a massive frame drop upon initiation, due to shear level of allocation, I was wondering if there is something I am missing or some text on solving this issue.

Update

Requested data members of my GLParticle class.

public class GLParticle {

    private GLSpriteSheet image = null;
    private float x;
    private float y;
    private float vX;
    private float vY;
    private float alpha;
    private float alphaStep;
    private boolean isDead;
    private long startTime;
    private long lifeTime;
    private final float u = 480f;
    private final float v = 504f;

}

Thanks Gary


Solution

  • You can create ten separate arrays of 2000 for each member of GLParticle, and use Flyweight Pattern. In this implementation, each GLParticle would be passed its index into the GLParticleSystem's arrays, along with an instance of GLParticleSystem that contains the arrays. This is slightly more cumbersome, but this is the first pattern to try when having lots of fine-grained objects becomes too expensive in terms of the CPU cycles.