• Post Reply Bookmark Topic Watch Topic
  • New Topic

How to measure Java Objects  RSS feed

 
elwali karkoub
Greenhorn
Posts: 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Heyyy experts

I need your help, I'm looking for some efficient methods that allow to know how many bytes a java objects use at RunTime, any propositions are welcomed


 
Paul Clapham
Sheriff
Posts: 22374
42
Eclipse IDE Firefox Browser MySQL Database
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
It would help if you clarified a couple of things.

First, consider this class:



How would you define the number of bytes used by an object of the Example class? You'll see that it contains only a reference to an array which can contain 42 String objects. So do you want just the size of the reference? Or that plus the size of the array it refers to? Or that plus the size of any String objects referred to by the array elements?

And second, what do you mean by an "efficient" method?
 
Ivan Jozsef Balazs
Rancher
Posts: 999
5
 
Syed Naved Ali
Greenhorn
Posts: 8
1
  • Likes 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
elwali karkoub wrote:Heyyy experts

I need your help, I'm looking for some efficient methods that allow to know how many bytes a java objects use at RunTime, any propositions are welcomed




Multiple ways depend on what you are looking for.
1 - Using Java Runtime by having a difference of total and free memory before and after object creation.


However, this approach is having few drawbacks as a single call to Runtime.freeMemory() proves insufficient because a JVM can increase its current heap size at any time.

2 - As mentioned earlier by using Instrumentation.
Java 8 ref, Instrumentation is having a method which returns object size.

long getObjectSize(Object objectToSize)
Returns an implementation-specific approximation of the amount of storage consumed by the specified object.

the way you can use this.

Class 1


Class 2


There is a trick to run the above code, you have to tell Java that class 2 is an agent and pass class 1 as the second argument, to do that first create a jar with class 2 and then in the manifest add Premain-Class: GetObjectSize then run as.
java -javaagent:GetObjectSize.jar Exp

3 - You can use Memory Measure this is a perfect solution for frequent use.


to run the above code you have to pass JVM agent argument as,
-javaagent:path/to/object-explorer.jar
 
Consider Paul's rocket mass heater.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!