The performance of the HashMap in JAVA8

后端 未结 1 1243
醉梦人生
醉梦人生 2021-02-11 01:34

I had a question when I learned the HashMap source code in java8。

Source code is so complicated, how much efficiency?

So I wrote a code about the hash conflict。<

相关标签:
1条回答
  • 2021-02-11 02:11

    Your test scenario is non-optimal for Java 8 HashMap. HashMap in Java 8 optimizes collisions by using binary trees for any hash chains longer than a given threshold. However, this only works if the key type is comparable. If it isn't then the overhead of testing to see if the optimization is possible actually makes Java 8 HashMap slower. (The slow-down is more than I expected ... but that's another topic.)

    Change your Test class to implement Comparable<Test> ... and you should see that Java 8 performs better than the others when the proportion of hash collisions is large enough.


    Note that the tree optimization should be considered as a defensive measure for the case where the hash function doesn't perform. The optimization turns O(N) worst-case performance to O(logN) worst-case.

    If you want your HashMap instances to have O(1) lookup, you should make sure that you use a good hash function for the key type. If the probability of collision is minimized, the optimization is moot.


    Source code is so complicated, how much efficiency?

    It is explained in the comments in the source code. And probably other places that Google can find for you :-)

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