Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a scenario where Java7's Hashmap implementation is preferred to Java8's implementation

As of Java8, our beloved HashMap behaves a little different. If the key implements a comparable interface, each hash would contain a balanced tree instead of a linked-list.

This reduces the worst-time complexity in case of collisions from O(n) to O(log(n)), see JEP180

Is there a situation in which upgrading from Java7 to Java8 would cause a degradation of performance of the HashMap as a result ?

like image 492
Uri Goren Avatar asked Nov 30 '16 09:11

Uri Goren


People also ask

How HashMap works internally in Java 8 with example?

In HashMap, hashCode() is used to calculate the bucket and therefore calculate the index. equals() method: This method is used to check whether 2 objects are equal or not. This method is provided by the Object class. You can override this in your class to provide your implementation.

How does the object's hashCode quality influence the HashMap performance?

since HashMap uses hashCode to calculate which bucket to use in the hashtable if you return 1 from hashCode you effectively make your HashMap 's performance be like an (unsorted) LinkedList 's performance. Returning random values will simply blow your HashMap up since equal objects will no longer have equal hashCode s.

How is a HashMap implemented?

Hashmap uses the array of Nodes(named as table), where Node has fields like the key, value (and much more). Here the Node is represented by class HashMapEntry. Basically, HashMap has an array where the key-value data is stored. It calculates the index in the array where the Node can be placed and it is placed there.


1 Answers

Java8 will use balanced tree in number of entries in the bucket in > N, where N is chosen empirically, and use list once again if that number is < K. I'd expect worse performance if number of entries in bucket changes in way that "treefyng / untreeifying" happens often. That might happen due to specific hash function.

Also I'm not sure if overhead for creating and querying tree is worth the profit for small N.

like image 148
dveim Avatar answered Oct 20 '22 17:10

dveim