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...
-
Possible duplicate of stackoverflow.com/questions/52353/…Invisible Arrow– Invisible Arrow2015-01-06 06:54:15 +00:00Commented Jan 6, 2015 at 6:54
-
1What makes you think your object is larger than a few kilobytes?user207421– user2074212015-01-06 07:17:51 +00:00Commented Jan 6, 2015 at 7:17
-
The serialized size of an object is not the same as the amount of memory it consumes on the Java heap.Louis Wasserman– Louis Wasserman2015-01-06 19:22:13 +00:00Commented Jan 6, 2015 at 19:22
Add a comment
|
1 Answer
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;
}