Java: Creating massive amount off new Objects

846 views Asked by At

I am working on a simple GameOfLife program and try out some Optimizations with it. My problem is that when i create the cells for the Game (small class with 6 Primitives) it can take a long time (especially when i create like 10000*10000 ).

So my question is if anyone has an idea how to do that faster?

cells = new Cell[this.collums][this.rows];

for (int x = 0; x < cells.length; x++) {
    for (int y = 0; y < cells[0].length; y++) {
        cells[x][y] = new Cell(x * this.cellSize, y * this.cellSize, this.cellSize);
    }
}
2

There are 2 answers

4
jrtapsell On

Creating a large amount of objects like this is going to be slow, there are 2 possible workarounds:

  • Use a boolean array (uses more memory) or BitSet (uses more CPU) to store the values, so you don't have the object overhead
  • Store Cell instances, but have 1 live and 1 dead cell, and then just use those instances to fill the array

The first one is quicker, but the second is more Object Orientated.

1
lexicore On

If you're up to big (or quasi-unlimited) game fields, you should probably not model single cells as objects in the first place.

The field in the Game of Life is normally not populated too much, so it's better to be modelled as a sparse matrix. There is a huge number of trick to optimize Game fo Life implementation - both from the data storage as well as performance (copmuting the field on the next step). Check this question, for instance:

Sparse matrices / arrays in Java

It might look like a good idea to have Cell instances representing single cells, and it might work for relatively small fields. But if you really aim for larger fields, this just won't work well. In this case you'll have to trade OO for efficiency.