Primitive vs reference storage in Java - Performance Comparison
We want to understand how storing data as primitive types or as references affects the time it takes to access or copy them.
How does the type of storage change the work done when handling data?
Analyze the time complexity of copying primitive and reference types.
int a = 5; // primitive
int b = a; // copy primitive
int[] arr1 = {1, 2, 3}; // reference
int[] arr2 = arr1; // copy reference
This code copies a primitive value and a reference to an array.
Look at what happens when copying each type.
- Primary operation: Copying a primitive value is a simple assignment.
- Primary operation: Copying a reference copies the address, not the whole object.
- How many times: Each copy happens once per assignment.
Copying a primitive value always takes the same small amount of time, no matter the value.
Copying a reference also takes the same small amount of time, regardless of the object size.
| Input Size (n) | Approx. Operations for Primitive Copy | Approx. Operations for Reference Copy |
|---|---|---|
| 10 | 1 | 1 |
| 100 | 1 | 1 |
| 1000 | 1 | 1 |
Pattern observation: Copying either a primitive or a reference is constant time, no matter the data size.
Time Complexity: O(1)
This means copying a primitive or a reference takes the same small, fixed amount of time regardless of data size.
[X] Wrong: "Copying a reference copies the whole object, so it takes longer for big objects."
[OK] Correct: Copying a reference only copies the address, not the object itself, so it stays fast no matter the object size.
Understanding how primitives and references are stored and copied helps you explain performance differences clearly in coding interviews.
"What if we copied the entire array instead of just the reference? How would the time complexity change?"
