Friday, July 16, 2021

Cost of implicit casting in Java

Java has implicit casting (e.g. from float to double). Curious to know what is the performance impact. For example:

// direct cast to double
methodWithDoubleAsParam((double)Integer.parseInt(anInteger))


vs

// explicitly cast to float and implicitly to double
methodWithDoubleAsParam((float)Integer.parseInt(anInteger))


For the above example, when looking at the generated byte code, the direct casting used the "i2d" (integer to double) instruction. The indirect and implicit casting used "i2f" and "f2d" instructions.

......
  private void lambda$run$2(java.lang.String[], int);
    Code:
       0: aload_0
       1: aload_1
       2: iconst_0
       3: aaload
       4: invokestatic  #20                 // Method java/lang/Integer.parseInt:(Ljava/lang/String;)I
       7: i2f
       8: f2d
       9: invokevirtual #21                 // Method dummy:(D)V
      12: return

  private void lambda$run$1(java.lang.String[], int);
    Code:
       0: aload_0
       1: aload_1
       2: iconst_0
       3: aaload
       4: invokestatic  #20                 // Method java/lang/Integer.parseInt:(Ljava/lang/String;)I
       7: i2d
       8: invokevirtual #21                 // Method dummy:(D)V
      11: return
......

 

On machine with OpenJDK 11, the extra cost for each call is about 2ns.

Full source code available.