How costly is Object Typecasting in terms of performance?
Should I try to avoid Typecasting when possible?
5 Answers
It is cheap enough that it falls into the category of premature optimization. Don't waste time even thinking or asking questions about it unless you have profiled your application and determined that it's a problem, and most importantly: don't compromise your design to avoid it.

- 342,105
- 78
- 482
- 720
Depending on what you mean by typecasting. There is "upcasting" which costs you nothing and there is "downcasting" which costs you a lot. The answer to the second also begins with "it depends". Usually I avoid downcasting in my code because, from my expierience, if it is overused in your code, it means that the design is bad. Which on the other hand does not necessarily have to mean that it should not be used at all.

- 10,350
- 9
- 51
- 93
-
3+1: While it might cost a bit in terms of performance, a good design is more important reason to avoid it. ;) – Peter Lawrey Jan 10 '12 at 12:54
JavaWorld: The cost of casting
Casting is used to convert between types -- between reference types in particular, for the type of casting operation in which we're interested here.
Upcast operations (also called widening conversions in the Java Language Specification) convert a subclass reference to an ancestor class reference. This casting operation is normally automatic, since it's always safe and can be implemented directly by the compiler.
Downcast operations (also called narrowing conversions in the Java Language Specification) convert an ancestor class reference to a subclass reference. This casting operation creates execution overhead, since Java requires that the cast be checked at runtime to make sure that it's valid. If the referenced object is not an instance of either the target type for the cast or a subclass of that type, the attempted cast is not permitted and must throw a java.lang.ClassCastException.

- 18,729
- 22
- 80
- 110
Typecasting will have a cost because the runtime type information has to be checked to ensure the cast will work. Compared to everything else, I doubt this will be significant, but you could try and measure it.
More generally, typecasting is (IMHO) a sign that something is not right in the design. Sure, sometimes you can't avoid it (working with legacy collections, for example), but I would definitely see if I could remove it.

- 18,795
- 6
- 56
- 82