簡體   English   中英

鋸齒狀陣列與一個大陣列?

[英]Jagged array versus one big array?

不太確定如何問這個問題,但是到目前為止,我有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),並且大多數情況下是

選項1的[from][to][dataX]

選項2的[(from | (to << 7) | (dataX << 14))]

由於具有一個大內存塊的優點,我建議使用一個大數組,但我也鼓勵編寫對該數組的特殊訪問器。

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

}

我只是用數組的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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM