11
I was doing some tests in Java and I noticed a very strange behavior. I made an array with two dimensions and populated the array in two different ways, filling with random numbers up to 2 31-1 and just changing its index. I’ve gained considerable performance by doing this, but I don’t understand why.
Here’s 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);
}
}
Note that I only changed a single line, the assignment of the array. In my tests I had an average of 90 seconds to:
array[j][i] = (int) (Math.random() * Integer.MAX_VALUE);
and 48 seconds to:
array[i][j] = (int) (Math.random() * Integer.MAX_VALUE);
I would very much like to understand the reason for this. Because that time difference in just reversing the array index?
Heed! Do not run this code on computers with little memory. There is a risk of crashing your operating system.
My question got a little weird, feel free to edit.
– Avelino