I have been benchmarked my multihreaded program using -agentlib:hprof=cpu=samples
and was surprised to find the following line in the results:
rank self accum count trace method
1 52.88% 52.88% 8486 300050 java.lang.Object.hashCode
I never explicitly call hashCode() in my program. What can be the reason for this? How can I understand the source for this time "waste" and whether it is normal or not?
Thanks, David
The hashcode() method returns the same hash value when called on two objects, which are equal according to the equals() method. And if the objects are unequal, it usually returns different hash values.
Hashing is a fundamental Computer Science concept which involves mapping objects or entities to integer values. These values are called hash values or hashcodes of those entities. The hashCode() method in Java is used to compute hash values of Java objects.
The purpose of the hashCode() method is to provide a numeric representation of an object's contents so as to provide an alternate mechanism to loosely identify it. By default the hashCode() returns an integer that represents the internal memory address of the object.
Most likely you're using very intensively a Map such as a HashMap.
HashMap used the hashCode
to distribute the objects. If you're using many objects with this data structure, is very important your .equals
and your .hashCode
method are properly implemented.
See: Effective Java Item 8: Always override hashCode when you override equals
One thing you should do is to check out matching stack trace to see who is calling it; changes are it is indeed HashMap.
But beyond this, I have noticed that hprof tends to vasty overestimate calls to hashCode(); and I really would like to know how and why. This is based on actually knowing rough performance profile of code; and I have seen 50% percent cpu use (by sampling), where it is all but certain that it absolutely will not take that long. Implementation of hashCode() just returns an int field, and method is final (on final object). So it is basically a profiler artifact of some sort... just no idea how or why, or how to get rid of it.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With