-
Notifications
You must be signed in to change notification settings - Fork 3
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
equals implemented without hashCode #37
Comments
Use Guava's Objects class to help with these implementations where appropriate. |
For these, we should use the Guava implementation with care - unless we can be sure that hotspot will optimize it away (I don't know either way). Some of these will be pretty frequently used. |
I'm generally of the mind that you do it the clearest way first, worry about minor gains after profiling indicates it is a problem. So let's use Guava since it is already integrated, then try alternatives if and only if we see a problem. |
I am not sure I get what you are talking about. What exactly would be optimized away? It's a matter of correctness. If you're going to implement one of: {hashCode, equals} then you need to make sure you also implement the other. I also agree with David, implement the obviously correct implementation and once you can prove a meaningful performance hit then optimize. There may be obvious implementations, in that case invoke the "where appropriate" clause of my comment. |
mgodave: basically, I was wondering whether hotspot would end up properly inlining the Guava Objects calls. |
HashCode and equals are pretty boilerplate type functionality. Maybe look into using this lombok for most cases and roll your own when what it does isn't good enough. |
I'm not sure why it would be any less likely to inline a call to Guava. Good hashcode implementations are actually non-trivial. Along the lines of performance decisions, I would argue that architecture and design at this point would make the biggest difference. If your object is immutable, cache the hashcode. If you object maybe should be immutable, then refactor and make the aforementioned change. Again, go the obviously correct route then optimize when you can prove a performance penalty! equals and hashcode should be the least of your performance worries at this point, especially since there is no empirical data to show they affect the critical path. |
@plytro I'd generally agree, but in this case it also has to play nice with |
There are several classes where we implement
equals
without implementinghashCode
, this is almost always a bad practice since it violates theObject
contract (Effective Java, Item 8). In some cases we use these objects in hash-based objects, which makes them especially critical to addhashCode
methods to if they overrideequals
.Override
equals
but nothashCode
and are used in a hashed collection:Override
equals
but nothashCode
:The text was updated successfully, but these errors were encountered: