开发者

Does instanceof operator generate a lot of overhead ? Why? [duplicate]

This question already has answers here: The performance impact of using instanceof in Java 开发者_开发问答 (24 answers) Closed 8 years ago.

I have a colleague here in my project, who is deeply against the use of instanceof operator, because it "generates a lot of overhead", what is the reason for that? Is it true?

Is there another way to check the type of the Object instead of using it?

Because I find it very useful in some occasions.


It does generate some overhead, combined with the subsequent casting. With recent version of Java the overhead has decreased. But anyway that's microoptimization - i.e. 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.


The main issue is that it generates code smell. If you use polymorphism instead this is a better design approach. The performance cost can be around 10 to 100 nano-seconds depending on the complexity of the call and how many implementing method you call from that line of code.


Actually, instanceof returning true and a cast to this type succeeding are not totally equivalent - the latter may succeed when the former returns false. So, even when there is something like this,

String s = someMethodReturningString();
Object o = s;
if (o instanceof String) {
   ...
}

the compiler has to generate at least a check o != null here.

In practice, it is neglectable, though.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜