I was doing some tests in Java and noticed a very strange behavior. I made a two-dimensional array and populated the array in two different ways, filling in random numbers up to 2 ^ 31-1 and just changing its index. I got a considerable performance gain by doing this, but I do not understand why.
Here is the code:
public class Array {
static int tamanhoX = 12000;
static int tamanhoY = 12000;
static int array[][] = new int[tamanhoX][tamanhoY];
static long tempoInicio = 0, tempoFim = 0;
static double mediaTempo = 0.0;
public static void main(String[] args) {
//Armazena o tempo das operações
long tempos[] = new long[10];
//Calcula o tempo da operação diversas vezes:
for (int i = 0; i < tempos.length; i++) {
//Armazena o valor retornado dentro do array: tempos[] na posição: i
tempos[i] = calculaTempo();
}
//Soma todos os valores armazenados no array: tempos[]
for (int i = 0; i < tempos.length; i++) {
mediaTempo += tempos[i];
}
System.out.println("Tempo total: " + (mediaTempo / 1000) + "s");
mediaTempo = mediaTempo / tempos.length;//Calcula média
System.out.println("Média de tempo é de: " + mediaTempo + "ms");
}
static long calculaTempo() {
//Armazena o momento de início da operação em milisegundos
tempoInicio = System.currentTimeMillis();
for (int i = 0; i < tamanhoX; i++) {
for (int j = 0; j < tamanhoY; j++) {
//Preenche com um valor aleatório:
//Mais lento
//array[j][i] = (int) (Math.random() * Integer.MAX_VALUE);
//Mais rápido
array[i][j] = (int) (Math.random() * Integer.MAX_VALUE);
}
}
//Armazena o tempo final da operação
tempoFim = System.currentTimeMillis();
System.out.println("Tempo: " + (tempoFim - tempoInicio) + "ms");
return (tempoFim - tempoInicio);
}
}
Notice that I've only changed a single line, that of assigning the array. In my tests I had an average of 90 seconds for:
array[j][i] = (int) (Math.random() * Integer.MAX_VALUE);
and 48 seconds for:
array[i][j] = (int) (Math.random() * Integer.MAX_VALUE);
I would love to understand the reason for this. Why does this time difference in just reverse the array index?
Caution! Do not run this code on computers with low memory. There is a risk of crashing your operating system.