Reputation: 1468
The equals()
method (and for that matter, also the compareTo()
method) can become a performance hotspot (e.g. in a high-traffic HashMap
). I was wondering what tricks folks have adopted to optimize these methods for these cases when they prove necessary.
IntelliJ IDEA, for example, generates the following:
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
...
}
What else have you come across that can be a guideline for writing a good performing equals()
method?
Upvotes: 5
Views: 4410
Reputation: 533530
I suggest making the HashMap larger is equals() is expensive (e.g. by decreasing the load factor). That way you will have less collisions and hopefully if(o == this) return true will match most often.
Upvotes: 0
Reputation: 405785
How to Write an Equality Method in Java is an extremely detailed and well written article explaining common pitfalls in writing an equality method and how to avoid them.
Upvotes: 5
Reputation: 37027
If your objects are within an environment where you are in complete control over what calls equals()
on them, then you should track what kind of comparisons you're performing, and tune your equals()
method appropriately.
You might be able to confirm that certain scenarios never happen, so do not need to be coded for within equals()
, such as:
null
You can also decide on an appropriate order for the checks you do perform, checking the most common failing reasons first.
Upvotes: 1
Reputation: 10814
I think you're already onto a key part of it because you said:
...when they prove necessary.
Remember the general rules for optimization:
I've heard them in a class years ago and as close as I can tell C2 is the source.
Upvotes: 4
Reputation: 4189
You might take a cue from string interning.
If your objects are immutable, you could implement your own "interning" by using a static factory method and stuffing the unique instances into a hash table. If you do this, then when the references are equal the objects are equal.
Upvotes: 2
Reputation: 4754
Check out a book entitle "Effective Java" by Joshua Bloch. It has some amazing tips and a whole section on this question. Goodluck!
Upvotes: 2
Reputation: 2115
Some general ideas that are not necessarily specific to equals()
equals()
on yourself or other objects, which can have a hidden performance impactIn addition to performance considerations, don't forget the equals
API contract to ensure that your equality is reflexive, symmetric, transitive and consistent and to always override hashcode()
as well, when you override equals()
.
Upvotes: 14