4

Possible Duplicate:
Which of these two for loops is more efficient in terms of time and cache performance
Why does the order of the loops affect performance when iterating over a 2D array?

I want to know the fastest method of going through a array, in big array I'm using its important. for example i have:

ushort[, , ,] map = new ushort[3000, 3000, 3, 3]; // [pointX, pointY, stack, lvl]

          for (int i = 0; i < 3000; i++)
              for (int j = 0; j < 3000; j++)
                  for (int k = 0; k < 3; k++)
                      for (int l = 0; l < 3; l++)
                         map[i, j, k, l] = 45001;

It's probably relevant as it depends on how those values are stored in memory. So in that case is it better to do this in that order - i->j->k->l or l->k->j->i?

Also, is it different for other languages?

Community
  • 1
  • 1
Jacek Grzelaczyk
  • 783
  • 2
  • 9
  • 21
  • 1
    This are not java syntax's. :) – Subhrajyoti Majumder Dec 10 '12 at 06:33
  • sorry because i didn't mean any specific language :) – Jacek Grzelaczyk Dec 10 '12 at 06:35
  • 3
    Sorry if I misunderstand, but is this the information you are looking for: http://stackoverflow.com/questions/9936132/why-does-the-order-of-the-loops-affect-performance-when-iterating-over-a-2d-arra? (That's for C, but up to a certain point it may apply to any language; and your question was originally tagged for several languages anyway.) – jogojapan Dec 10 '12 at 06:40

1 Answers1

2

It makes big difference on the way how to initialize the array in java, the following is pure java code to show the difference , you can refer to the code below to improve the efficiency:

public class MutipleArray {

    public static void main(String[] args) {
        long t0 = System.currentTimeMillis();
        int [][][][] map = new int[3000][3000][3][3];
        for (int i = 0; i < 3000; i++)
            for (int j = 0; j < 3000; j++)
                for (int k = 0; k < 3; k++)
                    for (int l = 0; l < 3; l++)
                       map[i][j][k][l] = 45001;
        long t1 = System.currentTimeMillis();
        System.out.println("Time for initializing the first Array:"+(t1-t0)+"ms");

        int [][][][] map2 = new int[3][3][3000][3000];
        for (int i = 0; i < 3; i++)
            for (int j = 0; j < 3; j++)
                for (int k = 0; k < 3000; k++)
                    for (int l = 0; l < 3000; l++)
                        map2[i][j][k][l] = 45001;
        long t2 = System.currentTimeMillis();
        System.out.println("Time for initializing the second Array:"+(t2-t1)+"ms");
    }
}

result:

Time for initializing the first Array:13570ms
Time for initializing the second Array:495ms

As a result, I would like to suggest you to use int [][][][] map = new int[3][3][3000][3000] instead in java.

feikiss
  • 344
  • 4
  • 14