Forums Register Login

How to calculate the size of an object

1
+Pie Number of slices to send: Send
Hey guys,
I would like to ask all of you a question that is: How to compute the size of an object?
Is the size of an object based on variables and methods?
If it is, please tell me the size of the object which is initialized form the class below:

Thanks and best regards!

2
+Pie Number of slices to send: Send
 

Duc Ta wrote:. . . How to compute the size of an object?

There is no simple way to do it; the size may vary from implementation to implementation. Objects occupy slightly more memory on a 64‑bit machine than a 32‑bit machine.


Is the size of an object based on variables and methods? . . .

No. The methods live in the Class<T> object and there is a reference to that Class<T> object in the object. Much of an object comprises references to each of its fields (not simply variables) and those fields may be reference types, and if they aren't null there will be another object somewhere representing the object pointed to; that will obviously vary in size. The name field will point to a String and that String will have a reference to a char[] whose size varies with the number of chars.

There is a rough rule that you count 8 bytes per reference type field on a 64‑bit machine, plus the sizes of the primitive fields, plus a bit more and I have forgotten how much more. At least I think those are the figures. So your Lion class is 4 for the int and 8 for the String plus however much else; the String is 8 for a reference to the char[], 4 for a cached hash code, and something and the char[] is 2 bytes per char plus 4 for the length field plus something.

Not a beginner's topic: moving discussion.
Yeast devil! Back to the oven that baked you! And take this tiny ad too:
a bit of art, as a gift, that will fit in a stocking
https://gardener-gift.com


reply
reply
This thread has been viewed 298 times.
Similar Threads
confusion in initializing
Help with reading from file and storing Strings into objects of a class
LinkedHashSet
polymorphism by using interface and inheritance
Encapsulation...
More...

All times above are in ranch (not your local) time.
The current ranch time is
Mar 28, 2024 11:43:29.