Java Overriding hashCode() method has any Performance issue?
Yes you can degrade the performance of a hashed collection if the hashCode method is implemented in a bad way. The best implementation of a hashCode method should generate the unique hashCode for unique objects. Unique hashCode will avoid collisions and an element can be stored and retrieved with O(1)
complexity. But only hashCode method will not be able to do it, you need to override the equals method also to help the JVM.
If the hashCode method is not able to generate unique hash for unique objects then there is a chance that you will be holding more than one objects at a bucket. This will occur when you have two elements with same hash but equals method returns false for them. So each time this happens the element will be added to the list at hash bucket. This will slow down both the insertion and retreival of elements. It will lead to O(n)
complexity for the get method, where n is the size of the list at a bucket.
Note: While you try to generate unique hash for unique objects in your hashCode implementation, be sure that you write simple algorithm for doing so. If your algorithm for generating the hash is too heavy then you will surely see a poor performance for operations on your hashed collection. As hashCode method is called for most of the operations on the hashed collection.
It would improve performance if the right data structure used at right place,
For example: a proper hashcode implementation in Object can nearly convert O(N) to O(1) for HashMap
lookup
unless you are doing too much complicated operation in hashCode()
method
It would invoke hashCode()
method every time it has to deal with Hash data structure with your Object and if you have heavy hashCode()
method (which shouldn't be)
It depends entirely on how you're implementing hashCode
. If you're doing lots of expensive deep operations, then perhaps it might, and in that case, you should consider caching a copy of the hashCode
(like String
does). But a decent implementation, such as with HashCodeBuilder
, won't be a big deal. Having a good hashCode
value can make lookups in data structures like HashMap
s and HashSet
s much, much faster, and if you override equals
, you need to override hashCode
.