Determining size of Java objects using Java API

Prior to Java 8 developers used various algos to determine the real size various objects. But now we can make use of class ObjectSizeCalculator to get the size of any Java object. It is part of nashorn sdk. This class takes care of object headers size, different size as per system bits, paddings etc.

package Performance;
 
import java.util.HashMap;
 
 
public class ObjectSizeCalculatorJavaSDK {
public static void main(String[] args) {
	System.out.println(ObjectSizeCalculator.getObjectSize(new HashMap<String, Integer>(100000)));
	System.out.println(ObjectSizeCalculator.getObjectSize(3));
	System.out.println(ObjectSizeCalculator.getObjectSize(new int[]{1, 2, 3, 4, 5, 6, 7 }));
	System.out.println(ObjectSizeCalculator.getObjectSize(new int[100]));
	System.out.println(ObjectSizeCalculator.getObjectSize(new String("aaaaaaaaaaaaaaaaa")));
	System.out.println(ObjectSizeCalculator.getObjectSize(new String("uday")));
	System.out.println(ObjectSizeCalculator.getObjectSize(new String("")));
	System.out.println(ObjectSizeCalculator.getObjectSize(""));
	System.out.println(ObjectSizeCalculator.getObjectSize(new Object()));
}
}

Here is the output on my 64 bit system :
48
16
48
416
80
48
40
40
16

Uday Ogra

Connect with me at http://facebook.com/tendulkarogra and lets have some healthy discussion :)

You may also like...

Leave a Reply

Your email address will not be published. Required fields are marked *