I have been struggling for finding the exact size of java objects. I have tried different options and non of them are working correctly. Then I tried to serialize the object and find the size of the serialized object. The size of the serialized object is very small, like in few kilo byte. So I doubted my method. I was wondering is it the correct way? Is there any problem you people see in this procedure? Please help...
Asked
Active
Viewed 744 times
0
-
Possible duplicate of http://stackoverflow.com/questions/52353/in-java-what-is-the-best-way-to-determine-the-size-of-an-object – Invisible Arrow Jan 06 '15 at 06:54
-
1What makes you think your object is larger than a few kilobytes? – user207421 Jan 06 '15 at 07:17
-
The serialized size of an object is not the same as the amount of memory it consumes on the Java heap. – Louis Wasserman Jan 06 '15 at 19:22
1 Answers
1
You can convert your object into a byte array using ObjectOutputStream
and ByteArrayOutputStream
:
public static int sizeof(Object obj) throws IOException {
ByteArrayOutputStream byteOutputStream = new ByteArrayOutputStream();
ObjectOutputStream objectOutputStream = new ObjectOutputStream(byteOutputStream);
objectOutputStream.writeObject(obj);
objectOutputStream.flush();
objectOutputStream.close();
return byteOutputStream.toByteArray().length;
}

Parth Soni
- 11,158
- 4
- 32
- 54

aurelius
- 3,946
- 7
- 40
- 73