Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How expensive is it to perform a cast operation Vs i++? [closed]

Tags:

java

casting

In Java, how expensive is to do a cast:

(MyObject) IObject;

versus:

i++;

assuming "int i = N" preceding it.

EDIT:

Disregard my direct comparison with (i++) for a second, if you would please. Let me rephrase this in more general terms: how expensive is casting in general? Choose your reference operation better than my naive "i++" example, take a simple variable declaration and assignment for instance, how does performing a cast compare to that in terms of VM bytecode/operations?

I used i++ as a measuring stick. That was a very bad idea. When they chose "meter" as a baseline they did much better. Is there a base measuring unit for operation cost in Java? A JVM op? I suppose this will depend to the native code the Java op compiles down to... anwyay, how expensive is casting? (you pick the measuring stick for me, I am bad at that)

like image 964
Robottinosino Avatar asked Jun 09 '12 15:06

Robottinosino


1 Answers

I will do a short answer on the 2nd part (how expensive is casting):

casting is very cheap and heavily optimized where it counts. if (o instanceof Clazz) ((Clazz)o) is absolutely free (the cast, not the check itself).

Overall if the cast can be proven by the compiler and constant folded it would cost nothing. Otherwise a load in the header of the object to determine the class is needed. Some JVM can use some bit of the pointer to store the class, it's how important it is. Anyways, even a load's likely to be cheap and hit the L1 cache. Virtually all casts branches are predicted correctly by the hardware - imagine how unlikely is getting ClassCastException (the slow path - and it doesn't matter optimization wise in such a case).

Arrays are generally significantly faster than collections framerwork and its generics for many a reason but casting plays a very small part, itself.

Last: blatant 'measure', i.e. microbenchmark is often an appalling idea, measuring the application performance as whole is the right way to go. Microbenchmarks require deep understanding how JVM optimizes (or doesn't) and you have to be sure you benchmark what you actually need. Overall it's an art on its own.

like image 148
bestsss Avatar answered Nov 03 '22 21:11

bestsss