Class Node {
 public Node() {
 }
}Node node = new Node();这个new的node占了多少内存啊?
我测了一下是16个字节,为什么是16个字节呢?
当我在Class Node加入一个public int a;之后,测出来是占用20字节,刚好是16 + 4那么是不是一个实例占用的内存就是16 + 内部数据结构占用的内存?

解决方案 »

  1.   

    this指针,方法表.. 应该是这些东西点用了吧
      

  2.   

    java并没有规定运行时实例占用的内存大小,每一种JVM实现所占用的内存数量可能是不同的。用Sun JRE 1.4.2 Client Hotspot JVM for Windows 测试的结果是:
    java.lang.Object 8字节
    java.lang.Float 16字节
    java.lang.Double 16字节
    java.lang.Integer 16字节
    java.lang.Long 16字节
    java.lang.String 2*(Length) + 38 ± 2
    java.util.Vector 80字节(空元素情况)
    object reference 4字节
    float array 4*(Length) + 14 ± 2从上面可以看出:
    1。对另一个实例的引用占4字节(相当32位平台的一个指针大小)
    2。基本的Object实例占8个字节,其中4个字节应当是引用对象本身的指针,另外4个字节可能是实例的标识,或者是GC用于管理内存可能用到的信息,不得而知。
    3。数组占用12-16字节,加上每个元素的大小乘以长度,如果数组元素是对象实例,这里计算的只是引用指针的大小,还要加上对象实例本身占用的内存。
    4。字符串占用36-40个字节,然后每个字符占用2个字节(Unicode)这里采用的测试方法是用getUsedMemory()对比实例构造前后的内存使用量,好像这和你的测试结果有所不同,不知道你是用什么方法测试的?
      

  3.   

    From http://www.jelovic.com/articles/why_java_is_slow.htmJava only allocates primitive data types like int and double and object references on the stack. All objects are allocated on the heap.For large objects which usually have identity semantics, this is not a handicap. C++ programmers will also allocate these objects on the heap. However, for small objects with value semantics, this is a major performance killer.What small objects? For me these are iterators. I use a lot of them in my designs. Someone else may use complex numbers. A 3D programmer may use a vector or a point class. People dealing with time series data will use a time class. Anybody using these will definitely hate trading a zero-time stack allocation for a constant-time heap allocation. Put that in a loop and that becomes O (n) vs. zero. Add another loop and you get O (n^2) vs. again, zero.
      

  4.   

    忘了说了,我是在KVM上测得
    我用的nokia S60模拟器用Runtime.getRuntime().freeMemory()来打印出每次new之后内存的情况,然后相减Node node0 = new Node();//
    //打印出剩余内存,减少16字节
    Node node1 = new Node();//
    //打印出剩余内存,减少16字节
    Node node2 = new Node();
    Node node3 = new Node();
    Node node4 = new Node();
    //打印出剩余内存,减少48字节