hashCode
and equals
? And who among the interviewees will answer the question how the Object.hashCode()
and System.identityHashCode()
calculated? How expensive is calling these methods? How can they be accelerated in HotSpot JVM? I bet hardly anyone will give the correct answer. Is that who reads this article.Object.hashCode
returns the address of an object in memory. Once upon a time, it probably was. For example, Dalvik VM still uses an object address that is shifted 3 bits to the right. However, such an implementation is unsuccessful: first, successively allocated objects will have consecutive hash codes; secondly, the garbage collector can move objects in memory by changing their addresses.Object.hashCode
.hashCode()
method, and then stored in the object header for subsequent calls. But for the first time it uses random! Convince yourself by looking at the OpenJDK sources ( get_next_hash
function).IdentityHashMap.put()
, which, in my opinion, is implemented quite effectively. The bottleneck turned out to be System.identityHashCode()
, on which IdentityHashMap relies. And only the first identityHashCode call on the object was slow. The second and subsequent calls, as we now know, take the stored value from the header.Object.hashCode
using the command line switch -XX:hashCode=n
(where n is from 0 to 5).-XX:hashCode=5
key -XX:hashCode=5
, I magically accelerated my algorithm by 30%! Why this option has not yet been defaulted remains a mystery ...hashCode
never returns 0, because 0 is considered a sign that the hash code for this object has not yet been generated: if (value == 0) value = 0xBAD ;
hashCode
, you can not only surprise your colleagues at the interview, but also make your algorithms more efficient.Source: https://habr.com/ru/post/165683/
All Articles