javaclassinstanceof

instanceof Vs getClass( )


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 practice ?


Solution

  • The reason that the performance1 of instanceof and getClass() == ... is different is that they are doing different things.

    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 practice2 ?

    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().


    1 - My answer was written assuming that there are sound performance results that show that getClass() is faster. The benchmark you presented is flawed in a number of respects, and we cannot trust the results it produces; see How do I write a correct micro-benchmark in Java?. Either way, the points I am making are independent of the performance!
    2 - 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". I recommend that everyone read No Best Practices if they haven't already done so.