Memory overhead of Java HashMap compared to ArrayList

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

    I don't have an answer for you either, but a quick google search turned up a function in Java that might help.

    Runtime.getRuntime().freeMemory();

    So I propose that you populate a HashMap and an ArrayList with the same data. Record the free memory, delete the first object, record memory, delete the second object, record the memory, compute the differences,..., profit!!!

    You should probably do this with magnitudes of data. ie Start with 1000, then 10000, 100000, 1000000.

    EDIT: Corrected, thanks to amischiefr.

    EDIT: Sorry for editing your post, but this is pretty important if you are going to use this (and It's a little much for a comment) . freeMemory does not work like you think it would. First, it's value is changed by garbage collection. Secondly, it's value is changed when java allocates more memory. Just using the freeMemory call alone doesn't provide useful data.

    Try this:

    public static void displayMemory() {
        Runtime r=Runtime.getRuntime();
        r.gc();
        r.gc(); // YES, you NEED 2!
        System.out.println("Memory Used="+(r.totalMemory()-r.freeMemory()));
    }
    

    Or you can return the memory used and store it, then compare it to a later value. Either way, remember the 2 gcs and subtracting from totalMemory().

    Again, sorry to edit your post!

    0 讨论(0)
提交回复
热议问题