1

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.

User_67128
  • 1,230
  • 8
  • 21
  • In my case it is 10 times slower even more when array size is in billion range. I saw that answer. – User_67128 Oct 03 '19 at 14:55
  • There is also this [post](https://stackoverflow.com/questions/732684/implementing-a-matrix-which-is-more-efficient-using-an-array-of-arrays-2d-o) – Nexevis Oct 03 '19 at 14:57
  • 1
    It would help to see the code used to access these arrays, not just the declarations. The only differences for speed that I can think of offhand are that there are two objects being referenced in the 2D version for each value you access, instead of just one, and array bounds checking is done twice instead of just once -- but it's hard to imagine those things in and of themselves adding up to a 10x speed difference. – kshetline Oct 03 '19 at 15:04
  • Check out . This actually helped me understanding how arrays work. – maxbur Oct 03 '19 at 15:07
  • 2
    It has to allocate 2 billion arrays for the second dimension. If you swap the coordinates(d1 = new byte[2][SIZE]), it'll probably run much faster – David Zimmerman Oct 03 '19 at 15:08
  • 2
    Probably you would not ask "why is making and using a billion tiny arrays slow", yet that is what happens here too, because `byte[SIZE][2]` isn't really a 2D array, it's an array of arrays. – harold Oct 03 '19 at 15:15
  • Changing d1 = new byte[2][SIZE] it works. You can post your comment as answer. @ David Zimmerman – User_67128 Oct 03 '19 at 15:17

1 Answers1

0

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.

User_67128
  • 1,230
  • 8
  • 21