For example:
a) int [x][y][z]
vs
b) int[x*y*z]
Initially thought I'd go with a) for simplicity.
I know that Java doesn't store arrays linearly in memory like C does, but what implications does this have for my program?
A one-dimensional array stores a single list of various elements having a similar data type. A two-dimensional array stores an array of various arrays, or a list of various lists, or an array of various one-dimensional arrays. It represents multiple data items in the form of a list.
1D arrays are just one row of values, while 2D arrays contain a grid of values that has several rows/columns. 1D: 2D: An ArrayList is just like a 1D Array except it's length is unbounded and you can add as many elements as you need.
This could be used to represent a model or parameters of a camera using matrices. For data storage, you can use multidimensional arrays of even larger sizes to represent chains of data structures or matrices for matrix math which have a slur of their own uses.
Usually the best thing to do when searching anwers for such questions is to see how the choices are compiled into JVM bytecode:
multi = new int[50][50]; single = new int[2500];
This is translated into:
BIPUSH 50 BIPUSH 50 MULTIANEWARRAY int[][] 2 ASTORE 1 SIPUSH 2500 NEWARRAY T_INT ASTORE 2
So, as you can see, the JVM already knows that we are talking about a multi dimensional array.
Keeping it further:
for (int i = 0; i < 50; ++i) for (int j = 0; j < 50; ++j) { multi[i][j] = 20; single[i*50+j] = 20; }
This is translated (skipping the cycles) into:
ALOAD 1: multi ILOAD 3: i AALOAD ILOAD 4: j BIPUSH 20 IASTORE ALOAD 2: single ILOAD 3: i BIPUSH 50 IMUL ILOAD 4: j IADD BIPUSH 20 IASTORE
So, as you can see, the multi-dimensional array is treated internally in the VM, no overhead generated by useless instructions, while using a single one uses more instructions since offset is calculated by hand.
I don't think that performance will be such an issue.
EDIT:
I did some simple benchmarks to see what's going down here. I chose to try different examples: linear read, linear write, and random access. Times are expressed in millisecs (and calculated using System.nanoTime()
. Here are the results:
Linear write
Linear read
Random read
The random one is a little misleading since it generates 2 random numbers for multi-dimensional array while just one for single dimensional (and PNRGs may consume some CPU).
Mind that I tried to let JIT work by benchmarking only after the 20th run of the same loop. For completeness my java VM is the following:
java version "1.6.0_17" Java(TM) SE Runtime Environment (build 1.6.0_17-b04) Java HotSpot(TM) 64-Bit Server VM (build 14.3-b01, mixed mode)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With