• Post Reply Bookmark Topic Watch Topic
  • New Topic

How to calculate the size of an object  RSS feed

 
Duc Ta
Ranch Hand
Posts: 46
2
  • Likes 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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!

 
Campbell Ritchie
Marshal
Posts: 56533
172
  • Likes 2
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!