A simple test to see how unnecessary casting will cost in Java.
// direct cast to double
methodWithDoubleAsParam((double)Integer.parseInt(anInteger))
vs
// explicitly cast to float and implicitly to double
methodWithDoubleAsParam((float)Integer.parseInt(anInteger))
git clone https://github.com/kitsook/casting-unnecessary.git
./gradlew build
./gradlew bootRun --args="1"
Output:
> Task :bootRun
. ____ _ __ _ _
/\\ / ___'_ __ _ _(_)_ __ __ _ \ \ \ \
( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \
\\/ ___)| |_)| | | | | || (_| | ) ) ) )
' |____| .__|_| |_|_| |_\__, | / / / /
=========|_|==============|___/=/_/_/_/
......
Extra time spent for each extra casting: 2.00ns
Looking at the generated bytecode (tested with openjdk 11.0.11 2021-04-20
) by running
javap -c -p build/classes/java/main/net/clarenceho/test/castingunnecessary/UnnecessaryCastingApplication.class
Output:
......
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
......
For direct casting, a single i2d (integer to double) instruction is used. With extra casting, it used i2f to convert integer to float and then f2d to convert the float to double.