Memory overhead of Java HashMap compared to ArrayList

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

    HashMap hold a reference to the value and a reference to the key.

    ArrayList just hold a reference to the value.

    So, assuming that the key uses the same memory of the value, HashMap uses 50% more memory ( although strictly speaking , is not the HashMap who uses that memory because it just keep a reference to it )

    In the other hand HashMap provides constant-time performance for the basic operations (get and put) So, although it may use more memory, getting an element may be much faster using a HashMap than a ArrayList.

    So, the next thing you should do is not to care about who uses more memory but what are they good for.

    Using the correct data structure for your program saves more CPU/memory than how the library is implemented underneath.

    EDIT

    After Grant Welch answer I decided to measure for 2,000,000 integers.

    Here's the source code

    This is the output

    $
    $javac MemoryUsage.java  
    Note: MemoryUsage.java uses unchecked or unsafe operations.
    Note: Recompile with -Xlint:unchecked for details.
    $java -Xms128m -Xmx128m MemoryUsage 
    Using ArrayListMemoryUsage@8558d2 size: 0
    Total memory: 133.234.688
    Initial free: 132.718.608
      Final free: 77.965.488
    
    Used: 54.753.120
    Memory Used 41.364.824
    ArrayListMemoryUsage@8558d2 size: 2000000
    $
    $java -Xms128m -Xmx128m MemoryUsage H
    Using HashMapMemoryUsage@8558d2 size: 0
    Total memory: 133.234.688
    Initial free: 124.329.984
      Final free: 4.109.600
    
    Used: 120.220.384
    Memory Used 129.108.608
    HashMapMemoryUsage@8558d2 size: 2000000
    

提交回复
热议问题