Memory overhead of Java HashMap compared to ArrayList

后端 未结 13 1851
不知归路
不知归路 2020-11-30 02:15

I am wondering what is the memory overhead of java HashMap compared to ArrayList?

Update:

I would like to improve the speed for searching fo

13条回答
  •  情歌与酒
    2020-11-30 02:28

    This site lists the memory consumption for several commonly (and not so commonly) used data structures. From there one can see that the HashMap takes roughly 5 times the space of an ArrayList. The map will also allocate one additional object per entry.

    If you need a predictable iteration order and use a LinkedHashMap, the memory consumption will be even higher.

    You can do your own memory measurements with Memory Measurer.

    There are two important facts to note however:

    1. A lot of data structures (including ArrayList and HashMap) do allocate space more space than they need currently, because otherwise they would have to frequently execute a costly resize operation. Thus the memory consumption per element depends on how many elements are in the collection. For example, an ArrayList with the default settings uses the same memory for 0 to 10 elements.
    2. As others have said, the keys of the map are stored, too. So if they are not in memory anyway, you will have to add this memory cost, too. An additional object will usually take 8 bytes of overhead alone, plus the memory for its fields, and possibly some padding. So this will also be a lot of memory.

提交回复
热议问题