instanceof运算符生成很多开销?为什么? [英] Does instanceof operator generate a lot of overhead ? Why?
问题描述
我在这个项目中有一个同事,对于使用 instanceof
运算符,因为它生成很多开销,这是什么原因?是真的吗?
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.
推荐答案
它确实产生一些开销,结合随后的铸造。使用最新版本的Java,开销减少了。
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.
instanceof
的真正的参数,是在许多情况下有更好的OOP方法来实现预期的行为。
The real argument against instanceof
is that in many cases there are better OOP ways to achieve the desired behaviour.
这篇关于instanceof运算符生成很多开销?为什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!