Java size of objects
|
|
|
Size of Objects in Java
Since Java purposefully hides many aspects of memory management, discovering how much memory your objects consume can be very helpfull especially when you are working with large about of memory.�The following tutorial will provide you with a small tool to help you to calculate the memory consumption of your objects.
Utillity class to calculate object size
To achieve our goal we will develop an interface in charge to instantiate the object we want to measure the size. We will then�measure heap size differences before and after several objects have been allocated and divide the difference by the number of times we have instantiated the subject class.
Let's define our Instantiator interface :
Our sizeOf utility class definition :
Java Size of objects usage
We have now an instantiator in charge of creating instances of the Java object we want to determine the size and the size of utility class to calculate it using the Runtime class.
In the following example we will define the size of an Integer object :
The result is
Integer
size = 16 bytes
Conclusion
You hold now all the cards to define your own evaluation for your objects. Depending on the size of your objects or object graph you want to test it can be usefull to change the OBJECT_COUNT variable in the SizeOfUtil class to reduce the time spent to calculate your object size.
Tags: java , objects , class , public , object , size , define , calculate , instantiator