案例一:
User
public class User { }
UserSizeTest
public class UserSizeTest { static final Runtime runTime=Runtime.getRuntime(); public static void main(String[] args) { final int count = 100000; User[] us=new User[count]; long heap1 = 0; for (int i = -1; i < count; ++i) { User user=null ; user=new User(); if (i >= 0) us[i] = user; else { user = null; heap1 = getUsedMemory(); } } long heap2 = getUsedMemory(); System.out.println("user大小:"+((float)heap2-heap1)/count+" bytes"); for (int i = 0; i < count; i++) { us[i]=null; } runTime.gc(); } static long getUsedMemory(){ return runTime.totalMemory()-runTime.freeMemory(); } }
结果:user大小:7.62576 bytes说明:
空对象占用8个字节
案例二:
public class User { boolean flag; long id; Date date ; }
运行测试类结果;user大小:23.50192 bytes
说明:
boolean 1+ long 8 + 引用类型 Date 4 =13 凑齐8的倍数 =1616+空对象 8 =24