What is the cost of casting in Java? Is it a good idea to avoid it?

casting, java

Solution

Type casts are usually an indicator that you should think about an alternative solution for your problem. After all, everything which can be checked at compile time will help the programmer.

However, sometimes type casts are unavoidable and in Generic code they happen often without the programmer ever noticing. Therefore, significant effort was made to make type cast quite fast.

In the past, a runtime type cast included the possibility that the super type hierarchy has to be traversed to find a match. Today, a type cast is nothing more than a number comparison plus a simple pointer comparison, if not optimized away when the analyzer could prove that the cast will always succeed.

In order to make type casting fast, every class knows its depth in the class hierarchy and has a table containing all super types. To test a class, its depth is compared and if the depth is lower, it can’t be a compatible class and the type cast fails. Otherwise, the table’s entry at the position equal to the depth of the check class must match exactly, so that’s all to test.

For example:

Object o=new JButton();
Container c=(Container)o;

Class `Container` has a depth of 3 and a the following table of superclasses:

Object
Component
Container

Class `JButton` has a depth of 5 and a the following table of superclasses:

Object
Component
Container
JComponent
JButton

Now the type cast checks:

- `JButton` has a depth of 5 which is `≥ 3`, the depth of `Container`, so the test might succeed

The third entry in the tables is checked and is an exact match:

Object          Object
Component       Component
Container   <=> Container
JComponent
JButton

So the hierarchy is not traversed anymore and the type cast operation is rather cheap.

Problem

I know there are two types of casting that are implicit and explicit castings. I read different questions on the StackOverflow such as this, this and this but I am still wondering what is the cost of casting in Java and is it a good idea to avoid it? What is the best practice for it? There are 2 types of casting: ``` String s = "Cast"; Object o = s; // implicit casting Object o = someObject; String s = (String) o; // explicit casting ``` In this second case, there is overhead in runtime, because the two type must be checked and in case that casting is not feasible, the JVM must throw a `ClassCastException`. Someone said it is better to profile the application to make sure casting is useful or not.

Original source

Related problems