• Post Reply Bookmark Topic Watch Topic
  • New Topic

how can we find the exact size of java Objects like used to find in C++ by sizeof() ?  RSS feed

 
Prabhat Ranjan
Ranch Hand
Posts: 397
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi,

As i know one way to find the sizeof java objects:

lets see we have a class

class test {

int a;
byte b;

String str;

}


Used Memory = Total memory() - free Memory()

is any another way to find the size of java Object ?
 
Prabhat Ranjan
Ranch Hand
Posts: 397
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
yes we can find the size of Object by another way that is part of jdk1.5 :

using the API java.lang.instrument.Instrumentation having method --> getObjectSize() .

I am correct ?

or any another way ?

is serialization not the correct way to find the java Object size().
 
fred rosenberger
lowercase baba
Bartender
Posts: 12565
49
Chrome Java Linux
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
A better question is "Why would you need to know?"

One of the goals of higher level languages is to remove all that stuff from the developer, so they don't have to deal with it/screw it up.

Even if you know, you can't do anything with it, since there is no pointer arithmetic operators. Sure, you can satiate your curiosity, but not much else.

 
Jesper de Jong
Java Cowboy
Sheriff
Posts: 16060
88
Android IntelliJ IDE Java Scala Spring
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
There is no easy way to do this in Java and there is no single answer to the question "how much memory does my object use?", because it depends on the implementation of the JVM you are using. It might differ between Java versions and operating systems.

Why do you need to know this?

Prabhat Ranjan wrote:Used Memory = Total memory() - free Memory()

This is not reliable, since the JVM is doing a lot of things in the background - there are threads running, for example for garbage collection, that can make the result of a call like this vary from moment to moment.
Prabhat Ranjan wrote:using the API java.lang.instrument.Instrumentation having method --> getObjectSize() .

That is not a practical method you can use, Instrumentation is an interface which is meant for special tools that do things with Java byte code.
Prabhat Ranjan wrote:is serialization not the correct way to find the java Object size().

No, the size of the serialized data of an object is not the same as the amount of memory that an object uses when it is live in memory.
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!