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?
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()
.
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