Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Jagged array versus one big array?

Tags:

c#

chess

Not so sure how to ask this question, but I have 2 ways (so far) for a lookup array

Option 1 is:

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

Option 2 is:

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

Both ways work nicely, but is there another (better) way of doing a fast lookup and which one would you take if speed / performance is what matter?

This would be used in a chessboard implementation (0x88) and mostly is

[from][to][dataX] for option 1

[(from | (to << 7) | (dataX << 14))] for option 2

like image 516
Fredou Avatar asked Apr 15 '13 12:04

Fredou


1 Answers

I would suggest using one large array, because of the advantages of having one large memory block, but I would also encourage writing a special accessor to that array.

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

}
like image 94
Dariusz Avatar answered Sep 24 '22 04:09

Dariusz