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

社会主义新天地 提交于 2019-12-30 06:45:10

问题


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.


回答1:


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.




回答2:


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)




回答3:


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.




回答4:


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.




回答5:


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.



来源:https://stackoverflow.com/questions/4973359/does-instanceof-operator-generate-a-lot-of-overhead-why

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!