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 ?