Casts

Casts also have a cost. Casts that can be resolved at compile time can be eliminated by the compiler (and are eliminated by the JDK compiler). Consider the two lines:

Integer i = new Integer(3);
Integer j = (Integer) i;

These two lines get compiled as if they were written as:

Integer i = new Integer(3);
Integer j = i;

On the other hand, casts not resolvable at compile time must be executed at runtime. But note that an instanceof test cannot be fully resolved at compile time:

Integer integer = new Integer(3);
if (integer instanceof Integer)
  Integer j = integer;

The test in the if statement here cannot be resolved by most compilers, because instanceof can return false if the first operand (integer) is null. (A more intelligent compiler might resolve this particular case by determining that integer was definitely not null for this code fragment, but most compilers are not that sophisticated.)

Primitive data type casts (ints, bytes, etc.) are quicker than object data type casts because there is no test involved, only a straightforward data conversion. But a primitive data type cast is still a runtime operation and has an associated cost.

Object type casts basically confirm that the object is of the required type. It appears that a VM with a JIT compiler is capable of reducing the cost of some casts to practically nothing. The following test, when run under JDK 1.2 without a JIT, shows object casts as having a small but measurable cost. With the JIT compiler running, the cast has no ...

Get Java Performance Tuning now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.