Search code examples
javaarraysprimitive-types

Why 2D arrays run significantly slower than 1D arrays in java


For one of my program I need large memory, I have done this with two different implementations, these are as follows:

  int SIZE = 1000000000;
  int[] rnums = new int[SIZE];
  byte[] d1 = new byte[2 * SIZE];
  byte[] d2 = new byte[2 * SIZE];


  int SIZE = 1000000000;
  int[] rnums = new int[SIZE];
  byte[][] d1 = new byte[SIZE][2]; 
  byte[][] d2 = new byte[SIZE][2];

Both programs work and produce the correct answer but the 2D implementation is very slower, as SIZE increases it becomes slower and slower.

The rest of the code is very similar, I don't understand why 2D causes that much delay.


Solution

  • As suggested by @David Zimmerman I've changed the code into following one:

      int SIZE = 1000000000;
      int[] rnums = new int[SIZE];
      byte[][] d1 = new byte[2][SIZE]; 
      byte[][] d2 = new byte[2][SIZE];
    

    And it works, runs normally.