我编写了一些代码来确定各种数据结构占用的内存。我使用classmexer api 来获取深/浅内存。我尝试了使用内部类节点实现的自定义整数堆栈上的调用。(我正在运行这个上ubuntu lucid
)
对于空栈,浅内存和深内存都是 16 字节对于 4 个整数的堆栈,深内存是 176 字节。这个数字让我很困惑,因为手动计算内存如下
4 个整数的堆栈:
object overhead = 16 bytes
reference to Node inst variable = 8
primitive type int variable = 4
padding = 4
total = 32
Each entry in stack has
Node = 40 bytes(inner class)
Integer field = 24
total = 64
所以,应该是 32+64N
对于 N = 4,这将是 288
那么,为什么 classmexer 将内存使用情况显示为 176 ?
还有一件事..我如何确定machine word size
我的系统。我查看了 lang.System 类,但找不到任何 api
这是我的代码
public class MemoryUsage {
private static void linkedListMemUsage(){
StackOfIntegers si1 = new StackOfIntegers();
long deepmem = MemoryUtil.deepMemoryUsageOf(si1);
long shallowmem = MemoryUtil.memoryUsageOf(si1);
System.out.println("\nfor an empty stack of integers");
System.out.println("*******************************");
System.out.println(si1.getClass().getSimpleName()+" took deep:"+deepmem+" bytes");
System.out.println(si1.getClass().getSimpleName()+" took shallow:"+shallowmem+" bytes");
StackOfIntegers si2 = new StackOfIntegers();
si2.push(new Integer(100));
si2.push(new Integer(200));
si2.push(new Integer(300));
si2.push(new Integer(400));
deepmem = MemoryUtil.deepMemoryUsageOf(si2);
shallowmem = MemoryUtil.memoryUsageOf(si2);
System.out.println("\nfor a stack of 4 integers");
System.out.println("*************************");
System.out.println(si1.getClass().getSimpleName()+" took deep:"+deepmem+" bytes");
System.out.println(si1.getClass().getSimpleName()+" took shallow:"+shallowmem+" bytes");
}
public static void main(String[] args) {
linkedListMemUsage();
}
class StackOfIntegers{
private int N;
private Node first;
public void push(Integer item){
Node old = first;
first = new Node();
first.item = item;
first.next = old;
N++;
}
private class Node{
Integer item;
Node next;
}
}
}