Does instanceof operator generate a lot of overhead ? Why?

This question already has an answer here:

  • The performance impact of using instanceof in Java 23 answers

  • It does generate some overhead, combined with the subsequent casting. With recent version of Java the overhead has decreased. But anyway that's microoptimization - ie you should not worry about it in the general case.

    The real argument against instanceof is that in many cases there are better OOP ways to achieve the desired behaviour.


    It may or may NOT generate any overhead if the compiler can prove the instance. Even if the compiler can not prove the target immediately the overhead is very little. A few cpu clocks (esp. if instanceof jump is properly predicted).

    Following casts after instanceof are usually free.

    (note: by the compiler I mean the JIT one)


    There is no serious overhead. It's almost certainly cheaper than a home-grown getType()-style solution. Casting, while not free, is also very cheap.

    As noted by Bozho it can be indicative of a flawed design, but in some situations it is the most pragmatic choice and so shouldn't be disregarded out of hand.

    链接地址: http://www.djcxy.com/p/76374.html

    上一篇: 如何在JAVA内部实现instanceof?

    下一篇: instanceof运算符是否会产生很多开销? 为什么?