java对象占用内存大小计算方式
案例一:
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
郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。