- boolean[][] b = new boolean[8000][1000];
- long s = System.currentTimeMillis();
- for ( int i = 0; i <1000 ; i++ ) {
- for ( int j = 0; j < 8000; j++ ) {
- b[j][i] = true;
- }
- }
- System.out.print(System.currentTimeMillis() - s);
执行结果:453
- boolean[][] b = new boolean[8000][1000];
- long s = System.currentTimeMillis();
- for ( int i = 0; i <8000 ; i++ ) {
- for ( int j = 0; j < 1000; j++ ) {
- b[i][j] = true;
- }
- }
- System.out.print(System.currentTimeMillis() - s);
执行结果:16
所以,在访问二维数组时,应该顺着子数组进行遍历,这样的访问效率是最高的。而在不同的子数组中来回遍历,就需要不断的重新计算指针偏移量,会导致效率非常低。

本文通过两个示例对比,展示了在Java中遍历二维数组的不同方式及其执行效率。实验表明,按照子数组顺序遍历能够显著提高访问速度。
443

被折叠的 条评论
为什么被折叠?



