使用instanceof帮助和java强制转换类型异常会影响性能吗?
我使用遗留库并且需要使用将对象转换为集合。 为了避免异常,我认为使用instanceof。 那么问题二: 1.如果我使用instanceof - 需要使用try..catch强制转换异常来避免异常? 2. 它会影响性能吗? 谢谢。
I use legacy library and need use cast Object to Collection.
For avoid exceptions I think to use instanceof.
So questions two:
1. If I use instanceof - need use try.. catch cast exception to avoid exceptions?
2. Does it hits performance?
Thanks.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
如果您使用
instanceOf
,则不需要try-catch(ClasscastException e)
。即使使用 null,instanceOf
也能保证工作。在当今的虚拟机中,转换并没有显示出任何可衡量的性能影响。相反,如果您发现转换过于频繁,请重新审视您的设计。
注意:由于类型擦除,
instanceof
不适用于泛型。If you use
instanceOf
then you do not needtry-catch(ClasscastException e)
.instanceOf
is guaranteed to work, even withnull
s.In today's VMs, casting does not show any measurable performance hit. Rather if you find doing casting too often, then revisit your design.
NOTE:
instanceof
does not work with Generics due to type erasure.Instanceof 并没有真正影响现代 JVM 的性能,任何影响都可以忽略不计。
这是有关此主题的文章 有一些数字!
Instanceof does not really hit on performance in modern JVMs, any impact would be negligible.
here's an article on this subject with some figures!
有时,在运行时了解对象的类型很有用,特别是在转换时。在 Java 中,无效的强制转换会导致运行时错误。许多无效的转换可以在编译时被捕获。但是,涉及类层次结构的强制转换可能会产生只能在运行时检测到的无效强制转换。 Java提供了运行时运算符instanceof来回答这个问题。它没有任何例外。
现代 JVM/JIC 编译器已经消除了大多数传统上“慢”操作的性能影响,包括 instanceof、异常处理、反射等。
请参阅 此 stackoverflow 链接
因此无需担心即可使用 instanceof,但您将无法在它们不在那里工作的集合中使用它。
Java泛型和instanceof
Sometimes, knowing the type of an object during run time is useful, specially in casting. In Java, an invalid cast causes a run-time error. Many invalid casts can be caught at compile time. However, casts involving class hierarchies can produce invalid casts that can be detected only at run time. Java provides the run-time operator instanceof to answer this question. It does not through any exception.
Modern JVM/JIC compilers have removed the performance hit of most of the traditionally "slow" operations, including instanceof, exception handling, reflection, etc.
please refer this stackoverflow link
hence go for instanceof without any worry, but you wont be able to use it in collection they dont work there.
java generics and instanceof