This post will introduce you to Java Autoboxing Performance Impact. Java provides the Autoboxing technique that helps developers write code cleaner and easier to read. But it also brings to use some impact of performances. If you are not familiar with the Java Autoboxing technique you can have a look at the tutorial Autoboxing and Unboxing Java Example. Let’s dig deeper.
Java Autoboxing Performance Impact
Use Autoboxing
We consider the java program below
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 |
import java.time.Duration; import java.time.Instant; class Main { public static void main(String[] args) { Instant start = Instant.now(); Long sum = 0L; for (long i = 0; i < Integer.MAX_VALUE; i++) { //Autoboxing: // Long = Long (unboxed) -> long + long // Long = (boxed) long sum = sum + i; } Instant end = Instant.now(); System.out.println("Sum: " + sum); System.out.println("Calculation time: "+Duration.between(start, end).getSeconds() + " seconds"); } } |
Run the above program, it will print the output below.
You can see in the output, the calculation time is 9 seconds. It is quite slow. The reason comes from the mixed-used of primitive type and wrapper class and the boxed and unboxed activities are repeatedly.
Use primitive type
Now we change a bit the above program, we just use a primitive type for the sum
variable as long
type. We have a program like this:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 |
import java.time.Duration; import java.time.Instant; class Main { public static void main(String[] args) { Instant start = Instant.now(); long sum = 0;// just use primitive type for (long i = 0; i < Integer.MAX_VALUE; i++) { sum = sum + i;//without autoboxing } Instant end = Instant.now(); System.out.println("Sum: " + sum); System.out.println("Calculation time: "+Duration.between(start, end).getSeconds() + " seconds"); } } |
Run the changed program, it will print the output below
As you see, the calculation time is just 1 second. It is faster than the first program.
So far, you have experienced Java Autoboxing Performance Impact in this post and learn from that to apply your code to get the best performance for your java program.
Happy Learning.
References
Autoboxing and Unboxing Java Example
Autoboxing in Java