• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

How to find the Size Of an Object ?

 
Venkat Ramayanam
Greenhorn
Posts: 5
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi,
Pls could some one tell me how to find the size of an object??
I know that there is no sizeof operator in java,but is there any direct way of finding it out?
Does the following code accomplish the task?

java.lang.instrument.Instrumentation.getObjectSize(Object objectToSize)
 
Rajah Nagur
Ranch Hand
Posts: 239
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Check this out
 
Peter Chase
Ranch Hand
Posts: 1970
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Why do you want to know the size of an object in memory? Java insulates the programmer from that sort of thing and 99% of the time, that's exactly what you want.
 
Pradeep Kadambar
Ranch Hand
Posts: 148
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
As Peter said

Why do you want to know the size of an object in memory?


There is no necessity for this. Many of us migrating form C/C++ to Java have the tendency to think in the same grounds as the former.

Here the articles clearly addresses the same issues.
Sizeof for Java

Data Size

I hope these articles will clear off your doubts.
 
Stan James
(instanceof Sidekick)
Ranch Hand
Posts: 8791
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
There are plenty of reasons to want to know this. In making a design choice I might prefer the one that takes less memory. I might have a good idea of how many objects I'll have and want to predict how much memory I'll need to buy. I might have an out of memory issue and want to know which object is causing it.

Unfortunately all those reasons don't help with the answer: we don't know.

We have used some tools from IBM that read verbose logs and give a report of object allocations - class name & size and so on. This helped us learn that a logger (for which we have no source) was making 5 or 6 copies of a many-megabyte log message (which we eliminated!), causing allocation errors in several unrelated areas of the app.
 
Peter Chase
Ranch Hand
Posts: 1970
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
If you need the size of an object for debugging memory problems, hprof will tell you the size, won't it? I thought the question was about getting the size programmatically within an ordinary application, which is something you can't do.

I've just been doing some hprof. Here's a little extract from my hprof output. You can clearly see the sizes (sz) of the objects and arrays.

 
It is sorta covered in the JavaRanch Style Guide.
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic