简体   繁体   中英

Java: Creating massive amount off new Objects

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);
    }
}

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM