Memory overhead of Java HashMap compared to ArrayList

后端 未结 13 1840
不知归路
不知归路 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:19

    All that is stored in either is pointers. Depending on your architecture a pointer should be 32 or 64 bits (or more or less)

    An array list of 10 tends to allocate 10 "Pointers" at a minimum (and also some one-time overhead stuff).

    A map has to allocate twice that (20 pointers) because it stores two values at a time. Then on top of that, it has to store the "Hash". which should be bigger than the map, at a loading of 75% it SHOULD be around 13 32-bit values (hashes).

    so if you want an offhand answer, the ratio should be about 1:3.25 or so, but you are only talking pointer storage--very small unless you are storing a massive number of objects--and if so, the utility of being able to reference instantly (HashMap) vs iterate (array) should be MUCH more significant than the memory size.

    Oh, also: Arrays can be fit to the exact size of your collection. HashMaps can as well if you specify the size, but if it "Grows" beyond that size, it will re-allocate a larger array and not use some of it, so there can be a little waste there as well.

提交回复
热议问题