Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Optimizing equals() method

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?

like image 918
Armadillo Avatar asked Jul 22 '09 01:07

Armadillo


1 Answers

Some general ideas that are not necessarily specific to equals()

  • Fail as early as possible. Similar to the snippet you posted, start with the broadest exclusion criteria first and then become more fine grained, so that the method can return as soon as possible
  • Compare only attributes required for equality. I've sometimes seen people compare every single piece of a information a class provides, even though only a handful of attributes actually play a semantic role for the equality of two class instances. This of course highly depends on your class and the design
  • Avoid equality recursion, if possible. Depending on what kind of class attributes you are comparing, you might get yourself into situations where you are recursively calling equals() on yourself or other objects, which can have a hidden performance impact

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

like image 68
Christian Hang-Hicks Avatar answered Oct 04 '22 02:10

Christian Hang-Hicks