How to calculate HashMap memory usage in Java?

后端 未结 3 1797
闹比i
闹比i 2020-12-01 04:47

I was asked in an interview to calculate the memory usage for HashMap and how much estimated memory it will consume if you have 2 million items in it.

3条回答
  •  野趣味
    野趣味 (楼主)
    2020-12-01 05:01

    you can't know in advance without knowing what all the strings are, and how many items are in each list, or without knowing if the strings are all unique references.

    The only way to know for sure, is to serialize the whole thing to a byte array (or temp file) and see exactly how many bytes that was.

提交回复
热议问题