开发者

Does using instanceof help and java cast type exception hits performance?

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 c开发者_JS百科ast exception to avoid exceptions? 2. Does it hits performance? Thanks.


  1. If you use instanceOf then you do not need try-catch(ClasscastException e). instanceOf is guaranteed to work, even with nulls.

  2. 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 does not really hit on performance in modern JVMs, any impact would be negligible.

here's an article on this subject with some figures!


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

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜