0

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...

3
  • Possible duplicate of stackoverflow.com/questions/52353/… Commented Jan 6, 2015 at 6:54
  • 1
    What makes you think your object is larger than a few kilobytes? Commented 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. Commented Jan 6, 2015 at 19:22

1 Answer 1

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;
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.