简体   繁体   English

数组列表 <Integer> vs ArrayList <String> -都存储从0到9的值..这需要更多的内存?

[英]ArrayList<Integer> vs ArrayList<String> - both storing values from 0 to 9 .. which takes more memory?

有人问我这个问题...... ArrayListInteger VS ArrayListString -从两个存储值09 ...这需要更多的内存?

Assuming lists are created as follows: 假设列表创建如下:

    List<Integer> integers = new ArrayList<>();
    integers.add(0);
    integers.add(1);
    // ...
    List<String> strings = new ArrayList<>();
    strings.add("0");
    strings.add("1");
    // ...

There two levels of answering this question. 有两个级别的答案。

First is about knowing memory consumption of Integer and String . 首先是了解IntegerString内存消耗。

So, a String with one character takes 40 bytes (32 on Java 8). 因此,具有一个字符的String需要40个字节(Java 8中为32个字节)。 An Integer takes 16 bytes. Integer需要16个字节。

On this level, list of strings takes more memory than list of integers. 在此级别上,字符串列表比整数列表占用更多的内存。

On the second level you have to know that string literals are interned and boxing an int with Integer.valueOf uses cache for values between -128 and at least 127 . 在第二个级别上,您必须知道字符串文字是被interned的,并且用Integer.valueOf将一个int装箱的值对-128到至少127之间的值使用高速缓存。 So basically both add("0") and add(0) will use cached objects and one could say that no additional memory is used. 因此,基本上add("0")add(0)都将使用缓存的对象,并且可以说没有使用额外的内存。

So depending on whether you consider string pool/integer cache, the answer is either "list of strings takes more memory" or "both lists take the same amount of memory". 因此,根据是否考虑字符串池/整数缓存,答案是“字符串列表占用更多内存”还是“两个列表占用相同的内存”。

If this is an interview question, you should probably give both answers. 如果这是一个面试问题,您可能应该同时给出两个答案。

ps. PS。 I personally wouldn't have known the size of String or Integer out of the head, but would have guessed String to take more memory. 我个人不会想知道StringInteger的大小,但是会猜到String会占用更多内存。

Here is a test result using this tool , it shows that ArrayList<Integer> occupies less memory: 这是使用此工具的测试结果,它表明ArrayList<Integer>占用更少的内存:

public static void main(String[] args) {
    ArrayList<Integer> integerArrayList = new ArrayList<>();
    ArrayList<String> stringArrayList = new ArrayList<>();
    for (int i = 0; i < 10; i++) {
        integerArrayList.add(i);
        stringArrayList.add(String.valueOf(i));
    }
    System.out.println(RamUsageEstimator.sizeOf(integerArrayList));  // 240
    System.out.println(RamUsageEstimator.sizeOf(stringArrayList));  // 560
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM