Cá estou eu sem sono e pensando num problema de programação … imagina a cena : preciso manter um memória para acesso aleatório uma matriz de 250 por 250 que vão representar eventos ocorridos em um mapa de um jogo, dai a pergunta que não quer calar é : será que matrizes multidimensionais no Java fazem diferença para acesso randômico ?
Porque sempre tem a opção de representar a matriz como um array bem grande, que o numero de elementos eh a quantidade de linhas x colunas, fiz alguns testes sem conclusão de quem tem melhor performance, pelo fato de serem dados aleatórios a cada teste acaba não ajudando muito nas conclusões, alguma sugestão ?
eis o código que usei para os testes
public class ArrayLengthCheckPerformance {
private static final int LINES = 250;
private static final int REGION_SIZE = 50;
private static final int COLUMNS = 250;
private static int[] foo1 = new int[COLUMNS * LINES];
private static int[][] foo2 = new int[COLUMNS][LINES];
public static void main(String[] args) {
int testsInner = 50;
int testsOuter = 100;
long total1 = 0;
long total2 = 0;
long dif = 0;
for (int i = 0; i < testsOuter; i++) {
long duration1 = runTest1(testsInner);
long duration2 = runTest2(testsInner);
dif = duration1 - duration2;
System.out.print("\nduration 1 / 2 = " + duration1 + " / "
+ duration2 + " dif(1-2) = " + dif);
total1 += duration1;
total2 += duration2;
}
dif = total1 - total2;
System.out.print("\n total duration 1/2 = " + total1 + " / " + total2
+ " dif(1-2) = " + dif);
}
private static long runTest2(int tests) {
long start = System.currentTimeMillis();
for (int i = 0; i < tests; i++) {
test2(10000);
}
long end = System.currentTimeMillis();
long duration = end - start;
return duration;
}
private static long runTest1(int tests) {
long start = System.currentTimeMillis();
for (int i = 0; i < tests; i++) {
test1(10000);
}
long end = System.currentTimeMillis();
long duration = end - start;
return duration;
}
private static void test1(int iterations) {
int[] location;
int x;
int y;
int pos;
int changeMe = 0;
for (int i = 0; i < iterations; i++) {
location = randomLocation();
x = (int) location[0] / REGION_SIZE;
y = (int) location[1] / REGION_SIZE;
pos = x + (y * LINES);
changeMe = foo1[pos] + x + y;
}
}
private static void test2(int iterations) {
int[] location; // use as y also ...
int x;
int y;
int changeMe = 0;
for (int i = 0; i < iterations; i++) {
location = randomLocation();
x = (int) location[0] / REGION_SIZE;
y = (int) location[1] / REGION_SIZE;
changeMe = foo2[x][y] + x + y;
}
}
private static int[] randomLocation() {
int x = (int) (Math.random() * COLUMNS * REGION_SIZE);
int y = (int) (Math.random() * LINES * REGION_SIZE);
int[] result = new int[2];
result[0] = x;
result[1] = y;
return result;
}
}