0

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.

user710818
  • 23,228
  • 58
  • 149
  • 207
  • The performance of instanceof and casting is quite good. I posted some timing in Java7 around different approaches to the problem here: http://stackoverflow.com/questions/16320014/java-optimization-nitpick-is-it-faster-to-cast-something-and-let-it-throw-excep/28858680#28858680 – Wheezil Mar 06 '15 at 12:38

3 Answers3

6
  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.

Swaranga Sarma
  • 13,055
  • 19
  • 60
  • 93
1

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!

Ashkan Aryan
  • 3,504
  • 4
  • 30
  • 44
1

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

Community
  • 1
  • 1
amod
  • 4,190
  • 10
  • 49
  • 75