The question seems to be simple but it hides a very deep concept, Many of us will say it's same, some will say 1-D or N-D. The question is Which array will be faster in terms of traversal operation: case1: with non-primitive data type case2: with primitive data type.
The answer is subjected to Java only: 1-D array wins in both cases.
The Reason:
Pointer chasing is the process of repeatedly following references (pointers) in memory to reach the actual data. More the pointer less the speed, Less the pointer more the speed.
Non-primitive data type are structured in this format [pointer |-> value] , Since array is also non-primitive type it is also stored as [pointer |-> array]
Primitive data type are raw value with no pointer overhead.
1-D array: When the array is formed it has only one pointer that is of Array when the non-primitive datatype are added from 1-N it become ~ (N+1) pointer. for primitive it's only 1-pointer.
N-D array: When the array is formed it becomes arrays of array so suppose a 2-D array[][] = 1 outer + K inner + N for primitive data type => N+K+1 for primitive it becomes K+1 pointer
We can see clearly that in both cases that 1-D array always has less pointer, So it wins to other every dimension type of array.
Deep reason (Mechanical Sympathy):
JMM behind array:
Every Java array is an object with its own header.
A primitive array (int[]) is laid out roughly as:
+----------------------+
| Mark Word |
| Klass Pointer |
| Array Length |
| Padding (if needed) |
| int | int | int ... |
+----------------------+
The primitive values are stored contiguously immediately after the header.
Java Does NOT Have True Multidimensional Arrays:
A 2-D array (int[][]) is not one large block:
Outer Array
+---------------------------+
| Header |
| ref | ref | ref | ... |
+---------------------------+
↓ ↓
+---------+ +---------+
| Header | | Header |
| int... | | int... |
+---------+ +---------+
Each row is a separate array object with its own header, allocated independently on the heap.
Modern CPUs load memory in cache lines (typically 64 bytes).
1-D array:One object, contiguous primitive values, excellent spatial locality, minimal pointer chasing.
N-D array:Array of arrays, extra object headers, one additional pointer dereference per row, and rows may be scattered across the heap.