I see gain in performance when using getClass()
and ==
operator over instanceOf
operator.
Object str = new Integer("2000");
long starttime = System.nanoTime();
if(str instanceof String) {
System.out.println("its string");
} else {
if (str instanceof Integer) {
System.out.println("its integer");
}
}
System.out.println((System.nanoTime()-starttime));
starttime = System.nanoTime();
if(str.getClass() == String.class) {
System.out.println("its string in equals");
} else {
if(str.getClass() == Integer.class) {
System.out.println("its integer");
}
}
System.out.println((System.nanoTime()-starttime));
Is there any guideline, which one to use getClass()
or instanceOf
?
Given a scenario: I know exact classes to be matched, that is String
, Integer
(these are final classes), etc.
Is using instanceOf
operator bad practise ?
The reason that the performance of instanceof
and getClass() == ...
is different is that they are doing different things.
instanceof
tests whether the object reference on the left-hand side (LHS) is an instance of the type on the right-hand side (RHS) or some subtype.
getClass() == ...
tests whether the types are identical.
So the recommendation is to ignore the performance issue and use the alternative that gives you the answer that you need.
Is using the
instanceOf
operator bad practice ?
Not necessarily. Overuse of either instanceOf
or getClass()
may be "design smell". If you are not careful, you end up with a design where the addition of new subclasses results in a significant amount of code reworking. In most situations, the preferred approach is to use polymorphism.
However, there are cases where these are NOT "design smell". For example, in equals(Object)
you need to test the actual type of the argument, and return false
if it doesn't match. This is best done using getClass()
.
Terms like "best practice", "bad practice", "design smell", "antipattern" and so on should be used sparingly and treated with suspicion. They encourage black-or-white thinking. It is better to make your judgements in context, rather than based purely on dogma; e.g. something that someone said is "best practice".