Reputation: 219
I have doubt in memory allocation for int and Integer variable in Java. For measuring memory i have used Instrumentation.getObjectSize() and it produces the same size for both the variables. Please find my code below:
ObjectSizeFetcher.java
import java.lang.instrument.Instrumentation;
public class ObjectSizeFetcher {
private static Instrumentation instrumentation;
public static void premain(String args, Instrumentation inst) {
instrumentation = inst;
}
public static long getObjectSize(Object o) {
return instrumentation.getObjectSize(o);
}
}
Test.java
public class Test {
public static void main(String[] args) throws Exception {
int i=0;
Integer i1 = new Integer(0);
long value = ObjectSizeFetcher.getObjectSize(i);
System.out.println(value);//prints 16
long value1 = ObjectSizeFetcher.getObjectSize(i1);
System.out.println(value1);//prints 16
}
}
In the above case both the variable size prints the same. My doubt is, int is primitive type and it size 4 bytes and Integer is reference type and its size is 16 bytes but in this case why produces 16 bytes for both the values? If both the take same amount of memory in heap means, it leads to memory issue in java right?
Upvotes: 4
Views: 8425
Reputation: 718768
int
is a primitive type and it size 4 bytes andInteger
is reference type and its size is 16 bytes. In this case, why does it retuyrn 16 bytes for both the values?
Because the ObjectSizeFetcher.getObjectSize(Object)
call is autoboxing the int
to an Integer
.
AFAIK, there is no standard API to measure the size of a primitive type, or a reference. One reason is that the size will depend on where / how it is stored. For example, a byte stored in a (large) byte[]
will most likely take less space than a byte stored as a field of an object. And a byte
held is a local variable could be different again. (There are issues of packing and alignment to tack account of.)
It is simple to write overloaded methods to return constant minimum size for each primitive types. References are a bit more tricky because the size of a reference depends on whether you are using a 32 or 64 bit JVM, and whether compressed oops are enabled.
Upvotes: 4
Reputation: 234665
i
gets auto-boxed to an Integer
when passed to getObjectSize
.
So you get the value of the size of promoted variable, not the original primitive int
.
To circumvent this behaviour, build overloads of getObjectSize
for the primitive cases:
public static long getObjectSize(int o) {
return Integer.SIZE / 8;
}
and so on.
Upvotes: 4