Two-dimensional arrays often come with performance losses. The benchmark sets up two 10 by 10 arrays. It then does a load and a store in the arrays.
public class Program {
public static void main(String[] args) {
int[] flat = new int[10 * 10];
// Flattened 10 x 10 array.
flat[0 + (4 * 10)] = 1;
int[][] two = new int[10][10];
// 10 x 10 two-dimensional array.
two[0][4] = 1;
long t1 = System.currentTimeMillis();
// Version 1: read, assign flattened array.
for (int i = 0; i < 100000000; i++) {
int value = flat[0 + (4 * 10)];
flat[9 + (9 * 10)] = value;
}
long t2 = System.currentTimeMillis();
// Version 2: read, assign 2D array.
for (int i = 0; i < 100000000; i++) {
int value = two[0][4];
two[9][9] = value;
}
long t3 = System.currentTimeMillis();
// ... Times.
System.out.println(t2 - t1);
System.out.println(t3 - t2);
}
}
131 ms, Flattened 1D array, load and store
256 ms, 2D array, load and store