2

I have read this article http://btoddb-java-sizing.blogspot.com/
Author explain how to calculate Objects size in Java. For example:

import jdk.nashorn.internal.ir.debug.ObjectSizeCalculator;

public final class Perfomance {

    static int number;

    static int anotherNumber;

    public static void main(String[] args) {
        System.out.println(ObjectSizeCalculator.getObjectSize(new Integer(2)));
    }
}

This code will show 16 because new object takes 12 bytes and inside Integer we have int(4 bytes) 12+4 = 16.

But consider this code:

System.out.println(ObjectSizeCalculator.getObjectSize(Integer.class));

Now its size 56 , moreover

 System.out.println(ObjectSizeCalculator.getObjectSize(Object.class));

Its show 288. How does it work. How allocated memory depends on class ?

Almas Abdrazak
  • 3,209
  • 5
  • 36
  • 80
  • In my machine `Integer.class` is 8840, `Object.class` is 288. Are you sure that you print a correct result? – dehasi Aug 03 '18 at 11:21
  • @dehasi Yes , in my machine x64 ubuntu 16.04 jdk 1.8.0_171 with OOPS its show 56 for Integer – Almas Abdrazak Aug 03 '18 at 11:23
  • I have 56 for `Byte.class` class if it helps in your investigation. I have jdk 1.8.0_144 on mac os. My guess `Integer` is `final` class, and this info helps to JIT to make optimizations. Keep in mind, you check sizes of `Class` objects – dehasi Aug 03 '18 at 11:32
  • 1
    Class object contains list of interfaces, classes, directly implemented methods, runtime annotations, fields. Look at this topic for dump, make few experiments and forget abouut it - it's just low-level magic. https://stackoverflow.com/questions/603013/dumping-a-java-objects-properties – Alexander Anikin Aug 03 '18 at 12:00

0 Answers0