简体   繁体   English

Java:从新对象中大量创建

[英]Java: Creating massive amount off new Objects

I am working on a simple GameOfLife program and try out some Optimizations with it. 我正在开发一个简单的GameOfLife程序,并尝试进行一些优化。 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 ). 我的问题是,当我为游戏(带有6个基元的小类)创建单元格时,可能会花费很长时间(尤其是当我创建类似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). 有很多技巧可以优化Game fo Life的实施-从数据存储和性能上进行优化(在下一步中对字段进行补偿)。 Check this question, for instance: 检查此问题,例如:

Sparse matrices / arrays in Java Java中的稀疏矩阵/数组

It might look like a good idea to have Cell instances representing single cells, and it might work for relatively small fields. Cell实例表示单个单元Cell似乎是一个好主意,并且可能适用于相对较小的字段。 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. 在这种情况下,您必须以OO换取效率。

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 使用布尔数组(使用更多的内存)或BitSet(使用更多的CPU)来存储值,这样就不会产生对象开销
  • Store Cell instances, but have 1 live and 1 dead cell, and then just use those instances to fill the array 存储单元实例,但有1个活动单元和1个死单元,然后仅使用这些实例填充数组

The first one is quicker, but the second is more Object Orientated. 第一个更快,但是第二个更面向对象。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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