我比较(使用 netbeans profiler)一些 java 集合,发现 ArrayIntList 比平面数组占用更多内存,即使您使用相同的初始容量创建它。根据其源代码,它只是在内部创建相同的数组。所以我不太明白。
您可以在下面看到源代码。
class ProfileFlatArray {
public static void main(String[] args) throws InterruptedException {
final int LEN = 5000000;
int[] array = new int[LEN];
Random rand = new Random();
for (int i = 0; i < LEN; i++) {
array[i] = rand.nextInt();
}
Thread.sleep(2000);
for (int i = LEN - 1; i > LEN / 2; i--) {
array[i] = 0;
}
Thread.sleep(5000);
System.gc();
Thread.sleep(2000);
System.out.print(array[rand.nextInt(LEN / 2 - 2)]);
}
}
还有乔达:
class ProfileArrayIntList {
public static void main(String[] args) throws InterruptedException {
final int LEN = 5000000;
ArrayIntList array = new ArrayIntList(LEN);
Random rand = new Random();
for (int i = 0; i < LEN; i++) {
array.add(i, rand.nextInt());
}
Thread.sleep(2000);
for (int i = LEN - 1; i > LEN / 2; i--) {
array.removeIntAt(i);
}
array.optimize();
Thread.sleep(5000);
System.gc();
Thread.sleep(2000);
System.out.print(array.get(rand.nextInt(LEN / 2 - 2)));
}
}
最佳答案
这是调用的结果
array.optimize();
它通过首先分配一个较小大小的数组来压缩新数组。这会导致内存碰撞。然后旧数组被 GC 处理,这会导致内存减少。因此,最终 optimize()
释放了一半的已用内存。
关于java - joda ArrayIntList(5000000) 与 int[5000000] 内存消耗,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20008290/