java - joda ArrayIntList(5000000) 与 int[5000000] 内存消耗

标签 java collections ram

我比较(使用 netbeans profiler)一些 java 集合,发现 ArrayIntList 比平面数组占用更多内存,即使您使用相同的初始容量创建它。根据其源代码,它只是在内部创建相同的数组。所以我不太明白。

您可以在下面看到源代码。

enter image description here

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/

相关文章:

java - 三重 DES 加密字符串生成 "\n"

java - 获取在 Android 中使用应用程序的总 RAM 大小

lua - Lua脚本在执行前是否加载到内存中?

java - Spring Cloud 配置 : how to use multiple configs

java - 使用 servlet 过滤器修改请求参数

Java:While循环和数组递增

java - 调用 list.remove(0) 时出现奇怪的 UnsupportedOperationException

c# - 无法将 IEnumerable 转换为指定类型

.net - CollectionViewSources 可以嵌套吗?

java - 监控 RAM 占用的工具