Joh*_*aul 62 java memory arrays jvm multidimensional-array
这个问题可能需要一些编译器知识才能回答.我目前正在开发一个项目,我将创建一个可能是其中的数组
int[2][veryLargeNumber]
Run Code Online (Sandbox Code Playgroud)
要么
int [veryLargeNumber][2]
Run Code Online (Sandbox Code Playgroud)
它在逻辑上没有区别,但我认为内存中的形式(以及因此大小)可能不同(也许问题应该是,编译器是否足够聪明地重新排列数组以适应它们)?
Pet*_*rey 53
Java实际上只实现了单维数组.它具有多维类型,但是二维数组实际上是作为数组阵列实现的.每个阵列的开销约为16个字节.最好int[2][x]将开销降至最低.
您可以完全使用辅助方法来避免此问题.
final int[] array = new int[2 * veryLargeNumber];
public int get(int x, int y) {
return array[idx(x, y)];
}
public void set(int x, int y, int val) {
array[idx(x, y)] = val;
}
private int idx(int x, int y) {
return x * 2 + y; // or x * veryLargeNumber + y;
}
Run Code Online (Sandbox Code Playgroud)
为了给自己提供这个,每个对象散列一个唯一的,生成存储在其Object头中的hashCode.
您可以从http://ideone.com/oGbDJ0看到每个嵌套数组本身就是一个对象.
int[][] array = new int[20][2];
for (int[] arr : array) {
System.out.println(arr);
}
Run Code Online (Sandbox Code Playgroud)
打印的内部表示int[],其[I由随后@接着哈希码()存储在头中.这不是有些人认为的,对象的地址.该地址不能用作hashCode,因为GC可以随时移动该对象(除非您有一个永远不会移动对象的JVM)
[I@106d69c
[I@52e922
[I@25154f
[I@10dea4e
[I@647e05
[I@1909752
[I@1f96302
[I@14eac69
[I@a57993
[I@1b84c92
[I@1c7c054
[I@12204a1
[I@a298b7
[I@14991ad
[I@d93b30
[I@16d3586
[I@154617c
[I@a14482
[I@140e19d
[I@17327b6
Run Code Online (Sandbox Code Playgroud)
如果您使用https://github.com/peter-lawrey/Performance-Examples/blob/master/src/main/java/vanilla/java/memory/ArrayAllocationMain.java关闭TLAB,您可以看到使用了多少内存.-XX:-UseTLAB
public static void main(String[] args) {
long used1 = memoryUsed();
int[][] array = new int[200][2];
long used2 = memoryUsed();
int[][] array2 = new int[2][200];
long used3 = memoryUsed();
if (used1 == used2) {
System.err.println("You need to turn off the TLAB with -XX:-UseTLAB");
} else {
System.out.printf("Space used by int[200][2] is " + (used2 - used1) + " bytes%n");
System.out.printf("Space used by int[2][200] is " + (used3 - used2) + " bytes%n");
}
}
public static long memoryUsed() {
Runtime rt = Runtime.getRuntime();
return rt.totalMemory() - rt.freeMemory();
}
Run Code Online (Sandbox Code Playgroud)
版画
Space used by int[200][2] is 5720 bytes
Space used by int[2][200] is 1656 bytes
Run Code Online (Sandbox Code Playgroud)
rad*_*doh 23
有趣的问题,我运行了一个简单的程序
int N = 100000000;
long start = System.currentTimeMillis();
int[][] a = new int[2][N];
System.out.println(System.currentTimeMillis() - start + " ms");
Run Code Online (Sandbox Code Playgroud)
结果导致了160 ms.然后我跑了另一个变种
int N = 100000000;
long start = System.currentTimeMillis();
int[][] a = new int[N][2];
System.out.println(System.currentTimeMillis() - start + " ms");
Run Code Online (Sandbox Code Playgroud)
结果导致了30897 ms.因此,我们确实在第一选择似乎很多更好.
She*_*lam 11
int[2][veryLargeNumber]
Run Code Online (Sandbox Code Playgroud)
创建两个阵列,项目verlarnumber
而
int[veryLargeNumber][2]
Run Code Online (Sandbox Code Playgroud)
创建非常多的具有两个项目的数组.
注意:数组创建有一个开销.第一个是首选