Does the javac or JIT optimize unnecessary autoboxing? Let's say we have a this fragment of code.
for(int i=0; i<100000; i++) {
f(i);
}
void f(Integer i) {
System.out.println(i);
}
How this fragment of code gets optimized? I guess f
will be inlined, but what about unnecessary boxing of int
(it's not being modified and never is null
). Let's assume the method is not called from any other fragment of code. Will there be any difference if the method signature wasvoid f(final Integer i)
?
Autoboxing and unboxing lets developers write cleaner code, making it easier to read. The technique lets us use primitive types and Wrapper class objects interchangeably and we do not need to perform any typecasting explicitly.
Autoboxing is the automatic conversion that the Java compiler makes between the primitive types and their corresponding object wrapper classes. For example, converting an int to an Integer, a double to a Double, and so on. If the conversion goes the other way, this is called unboxing.
In the java. lang package java provides a separate class for each of the primitive data type namely Byte, Character, Double, Integer, Float, Long, Short. Converting primitive datatype to object is called boxing.
Boxing refers to turning a primitive to an object wrapper version (e.g. Java int to java. lang. Integer ), unboxing is the opposite, and autoboxing is when it happens automatically (e.g. when Java needs a primitive in a place for only objects). Kotlin does autobox as needed internally.
The OpenJDK and HotSpot JVM 5 - 8 don't optimise them away, unless they are not used (and even then not always)
However, it is important to have a sense of perspective when you ask these problem or answer them. Autoboixing is trivial compared to the code of converting a number into a String (the way the JVM does it anyway) and this is trivial by comparison to writing to the console. If you take out the System.out.println() this will save 99.99%+ of the time so worrying about autoboxing here is worrying about the wrong things.
In your specifc case, it cannot optimise way the autoboxing because PrintStream.println(Object) is called. The JVM generally doesn't understand what libraries do and it can't make the assumption that calling PrintStream.println(int) would do the same thing.
The JVM is free to do whatever optimisation it likes, so it is possible that some JVMs would optimise this.
It's bad practice to assume it will though and for every JVM that does there may well be several that don't.
Just change the method to accept the type in the same level of boxing as it uses inside it..
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With