Optimization of the equals () method

A method equals()(and in this respect also a method compareTo()) can become a performance access point (for example, in high traffic mode HashMap). I was wondering what kind of tricks people took to optimize these methods for these cases when they prove the need.

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 do you mean, this could be a guideline for writing a good method equals()?

+5
source share
7 answers

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

  • . , , ,
  • , . , , , . , , .
  • , . , , , equals() , .

equals API-, , reflexive, , hashcode(), equals().

+14

, , :

... .

:

  • ...

C2 .

+5

Java - , .

+5

, " Java" . . !

+2

string interning.

, "", factory -. , , , .

+1

, , equals() , , , equals().

, , , equals(), :

  • null
  • self

, , .

+1

I suggest making the HashMap more equal to () expensive (e.g. by decreasing the load factor). This way you will have less conflicts and hopefully if (o == this) return true will be the most common.

0
source

All Articles