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.
One of the foremost concerns related to casting in Java refers directly to the two type groups in Java. The two types of groups are primitive and reference. The first attention of this discourse would go to the casting of primitives to ensure type conversion.
Casting isn't very expensive. Of course, if you have a loop that runs a million times a second it might make sense to avoid casting to save some performance, otherwise it won't really cause performance issues. The real problem with casting is that it's cheating type safety.
Type casting is a way of converting data from one data type to another data type. This process of data conversion is also known as type conversion or type coercion. In Java, we can cast both reference and primitive data types. By using casting, data can not be changed but only the data type is changed.
Overall, being “type-cast” is not necessarily a bad thing, in fact it helps Hollywood produce quality movies. Actors and actresses hone a craft and make a certain type of character and role theirs and it improves the movies they make.
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 succeedThe 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.
In this second case, there is overhead in runtime, because the two type must be checked and in case that casting is not feasible, JVM must throw a ClassCastException.
Not necessarily, it is very likely that for a simple case like this the JIT will be able to figure out that the cast will always work and will optimise the check away. Running a microbenchmark confirms the assumption:
Benchmark Mode Samples Score Error Units
c.a.p.SO26335959.cast avgt 5 3.177 ± 0.060 ns/op
c.a.p.SO26335959.noCast avgt 5 3.174 ± 0.108 ns/op
In more complicated situations, branch prediction will work in your favour too.
Bottom line, as usual: measure, don't guess!
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With