8

不太确定如何问这个问题,但我有 2 种方法(到目前为止)查找数组

选项 1 是:

bool[][][] myJaggegArray;

myJaggegArray = new bool[120][][];
for (int i = 0; i < 120; ++i)
{
  if ((i & 0x88) == 0)
  {
    //only 64 will be set
    myJaggegArray[i] = new bool[120][];
    for (int j = 0; j < 120; ++j)
    {
      if ((j & 0x88) == 0)
      {
        //only 64 will be set
        myJaggegArray[i][j] = new bool[60];
      }
    }
  }
}

选项 2 是:

bool[] myArray;
//                [998520]
myArray = new bool[(120 | (120 << 7) | (60 << 14))];

两种方式都很好,但是是否有另一种(更好的)方式进行快速查找,如果速度/性能很重要,您会采用哪种方式?

这将用于棋盘实现(0x88),主要是

[from][to][dataX]对于选项 1

[(from | (to << 7) | (dataX << 14))]对于选项 2

4

2 回答 2

2

我建议使用一个大数组,因为有一个大内存块的优点,但我也鼓励为该数组编写一个特殊的访问器。

class MyCustomDataStore
{ 
  bool[] array;
  int sizex, sizey, sizez;

  MyCustomDataStore(int x, int y, int z) {
    array=new bool[x*y*z];
    this.sizex = x;
    this.sizey = y;
    this.sizez = z;
  }

  bool get(int px, int py, int pz) {
    // change the order in whatever way you iterate
    return  array [ px*sizex*sizey + py*sizey + pz ];
  }

}
于 2013-04-15T12:47:34.350 回答
1

我只是用 z-size <= 64 的 long 数组更新 dariusz 的解决方案

edit2:更新为 '<<' 版本,尺寸固定为 128x128x64

class MyCustomDataStore
{
     long[] array;

     MyCustomDataStore() 
     {
          array = new long[128 | 128 << 7];
     }

     bool get(int px, int py, int pz) 
     {
          return (array[px | (py << 7)] & (1 << pz)) == 0;
     }

     void set(int px, int py, int pz, bool val) 
     {
          long mask = (1 << pz);
          int index = px | (py << 7);
          if (val)
          {
               array[index] |= mask;
          }
          else
          {
               array[index] &= ~mask;
          }
     }
}

编辑:性能测试:使用 100 次 128x128x64 填充和读取

long: 9885ms, 132096B
bool: 9740ms, 1065088B
于 2013-04-15T13:16:54.550 回答