Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

java

casting

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.

like image 252
Jack Avatar asked Oct 13 '14 08:10

Jack


People also ask

What should we concern when casting in Java?

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.

Is type casting costly?

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.

What is the point of casting in Java?

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.

Is type casting bad?

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.


2 Answers

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.

like image 190
Holger Avatar answered Oct 04 '22 00:10

Holger


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!

like image 27
assylias Avatar answered Oct 03 '22 23:10

assylias