可能重复:
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?
我想知道通过数组的最快方法,在大数组中我正在使用它的重要数据。例如我有:
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;
它可能是相关的,因为它取决于这些值如何存储在内存中。因此,在这种情况下,最好按此顺序执行此操作 - i-&gt; j-> k-> l或l-> k-> j-&gt; i?
另外,它与其他语言不同吗?
答案 0 :(得分:2)
它在如何在java中初始化数组的方式上有很大的不同,以下是纯java代码来显示差异,你可以参考下面的代码来提高效率:
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");
}
}
结果:
Time for initializing the first Array:13570ms
Time for initializing the second Array:495ms
因此,我建议您在java中使用int [] [] [] [] map = new int [3] [3] [3000] [3000]。