3

Possible Duplicates:
sizeof java object
In Java, what is the best way to determine the size of an object?

Hi,

Why is there no sizeof in java? how can one know how big is an object?

thank you

Community
  • 1
  • 1
user719313
  • 43
  • 4

3 Answers3

1

Use a profiler if you want to know your how much memory your program is using.

Basically, the size of an object is one of those things you don't need to be very aware of in Java. Makes you won't why it is so essential in C/C++. ;)

The longer answer is that you can use Instrumentation.getSizeOf(Object) but its not simple to use.

Peter Lawrey
  • 525,659
  • 79
  • 751
  • 1,130
1

Yes there is. Here is an example of how this can be done. Another way is to declare at object and take the Runtime.freeMemory() both before and after the object has been instantiated than look at the difference.

John Kane
  • 4,383
  • 1
  • 24
  • 42
  • 3
    That's not necessarily correct -- because if for instance the JVM decides to resize (make larger) the heap space you will find out that you have more free space after the allocation than before! – Liv Apr 21 '11 at 16:36
  • If you do this repeatedly for many objects you can get the right size most of the time. ;) – Peter Lawrey Apr 21 '11 at 16:39
  • Yes, I know that it is not perfect but with enough object instances this should give a fairly reasonable estimate – John Kane Apr 21 '11 at 17:23
  • The important thing is to do the test repeatedly. If you do to many objects you are likely to get a GC which will give you strange results, even a negative result. – Peter Lawrey Apr 22 '11 at 08:19
0

This is a complex discussion because what do you mean by "size"? Do you mean for instance how many bytes does Java take to represent an int, or a char etc? Or do you mean how many bytes does it use to store the reference to the object? Or how many bytes do the internal structures employed by the JVM use to create and store all the data in that object? I would venture to guess the answers to the last 2 questions is OS-dependent and I don't think you can standardize it. (For instance on 64-bit machines, it's easier for the OS to deal with a 64-bit integer at a time rather than 32 -- so quite likely internally a Java int will be represented on 8 bytes, even though java int's store only 32-bit values.)

There are ways to find out some of these -- for instance look at this: http://devblog.streamy.com/2009/07/24/determine-size-of-java-object-class/ -- but they won't be consistent across OS's.

Liv
  • 6,006
  • 1
  • 22
  • 29