在java专家By Tony Sintes的文章"Discover how mUCh memory an object consumes " 里面提到了应该用Runtime.getRuntime().totalMemory();并且计算两次之差来得到消耗的内存量。
By Tony Sintes的源代码:
public class Memory { private final static int _SIZE = 500; public static void main( String [] args ) throws Exception { Object[] array = new Object[_SIZE]; Runtime.getRuntime().gc(); long start = Runtime.getRuntime().totalMemory(); for (int i = 0; i < _SIZE; i++) { array[i] = new Object(); } Runtime.getRuntime().gc(); long end = Runtime.getRuntime().totalMemory(); long difference = ( start - end ) / _SIZE; System.out.println( difference + " bytes used per object on average" ); } }
实际上,这种方法基本上正确了,但是By Tony Sintes疏忽了一点,就是仅仅Runtime.getRuntime().gc();并不能真正完成垃圾收集,也就是说实际上jvm的内存此时并不是稳定的。