Unboxing in Java - Time & Space Complexity
We want to understand how unboxing affects the time it takes for a program to run.
Specifically, we ask: how does unboxing operations grow as the input size changes?
Analyze the time complexity of the following code snippet.
Integer[] numbers = new Integer[n];
int sum = 0;
for (int i = 0; i < n; i++) {
sum += numbers[i]; // unboxing happens here
}
System.out.println(sum);
This code sums up values stored as Integer objects by unboxing them to int.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Unboxing each Integer to int inside the loop.
- How many times: Exactly once for each element, so n times.
Each element requires one unboxing operation, so as the number of elements grows, the total work grows proportionally.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 10 unboxing operations |
| 100 | 100 unboxing operations |
| 1000 | 1000 unboxing operations |
Pattern observation: The work grows in a straight line with input size.
Time Complexity: O(n)
This means the time to complete the sum grows directly in proportion to the number of elements.
[X] Wrong: "Unboxing is free and does not affect performance."
[OK] Correct: Each unboxing is a small operation that happens every time you convert from Integer to int, so it adds up when done many times.
Understanding how unboxing affects time helps you write efficient code and explain performance in real projects.
"What if we replaced the Integer array with an int array? How would the time complexity change?"
