Netherwire
Netherwire

Reputation: 2787

Is there any benefit to override equals() for concrete type in java?

I need to compare hundreds of points to find path on 2D grid and I am really looking for performance. I overridden equals() in my Point's class:

@Override
public boolean equals(Object o)
{
    if (o instanceof Point)
    {
        Point that = (Point) o;
        return that.i == this.i && that.j == this.j;
    }
    return false;
}

That's pretty good, because it's possible to compare my Point to objects (which is used in ArrayList.contains()), but I often need to compare Points among themselves. So I overloaded equals():

public final boolean equals(Point other)
{
    return (i == other.i) && (j == other.j);
}

The question is: is there any benefit from the second method? Is this faster to compare two Point instances in cases when they are compared directly, and instanceof and cast are not required:

boolean result = onePoint.equals(otherPoint);

About platform: the code is compiled using android SDK(19) on android, and it is AOT-compiled using avian on iOS.

Thanks a lot.

Upvotes: 1

Views: 187

Answers (2)

janos
janos

Reputation: 124646

Quoting from this other answer: https://stackoverflow.com/a/103600/641955

As Donald Knuth wrote, "We should forget about small efficiencies, say about 97% of the time: premature optimization is the root of all evil." The performance of instanceof probably won't be an issue, so don't waste your time coming up with exotic workarounds until you're sure that's the problem.

So no, don't use the custom equals method until you benchmarked your program and identified the standard one to be a bottleneck, which is extremely unlikely.

There are probably other things you can improve. For example you mention using ArrayList.contains, which is an O(N) operation. Consider using a Set instead to make it O(1). This is just an example. A fun fact is that programmers are notoriously bad at guessing bottlenecks. Measure first, and focus your energy where it's actually needed.

Upvotes: 2

John Bollinger
John Bollinger

Reputation: 180201

The overloaded equals() method complicates your class and your life, probably for little practical benefit. If you measured the performance of your application and found that any appreciable amount of time was spent in Point.equals(), then it might be appropriate to look for ways to speed it up, such as by providing a lighter-weight overload. Otherwise, don't.

Upvotes: 0

Related Questions