Tuesday, November 14, 2006

Again: equals() confusions

I was wrong and everyone is wrong who claims that such construct:

if (getClass() != obj.getClass()) {
return false;
}
is more efficient than this one:

if (!(obj instanceof ExampleBean)) {
return false;
}
It wasn't difficult to check the performance and I must say that instanceof is slightly FASTER!!! than != operator in this case. I invoked 10.000.000 time equals() method on my simple bean and the result were very similar but equals() using instanceof operator was faster every time at about 50 millis (it's not much BUT...). I checked it even with small hierarchy i.e. I created class A, class B extends A and class C extends B and checked it again - still instanceof is faster.

I also checked third possibility, namely:

if (!getClass().isAssignableFrom(obj.getClass())) {
return false;
}
but it was three times slower than two other constructs.

Once again: REMEMBER to use instanceof operator in all persistent objects when you use Hibernate (see hibernate docs), but also keep in mind that this operator breaks the equals() method contract - it is not SYMMETRICAL.

No comments: