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.
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 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
精彩评论