与Primitive`int`相比,使用原始`byte`增加了占用的空间

时间:2015-03-13 20:45:34

标签: java memory-management

我有一个示例程序,我正在测试占用的内存。我不知道我哪里出错了,或者我实施的是错误的。但是当我使用byte而不是int时,JVM占用的内存会增加。以下是两个类文件:

Class Test1:

public class Test1 {
    public Test1 node1, node2;
    DATATYPE a, b; // DATATYPE is Primitive `int` or Primitive `byte`
}

课程测试:

public class Test {
    public static void main(String args[]) throws IOException
    {
        System.out.println(getMemory());

        Test1 root = new Test1();
        Test1 currNode = root;
        for(int i = 0; i < 10000000; i++)
        {
            currNode.node1 = new Test1();
            currNode.a = 10;
            currNode.b = 10;
            currNode.node2 = currNode;
            currNode = new Test1();
        }

        System.out.println(getMemory());
    }

public static String getMemory()
    {
        HashMap<String, Double> hm = new HashMap<String, Double>();
        Runtime runtime = Runtime.getRuntime();
        hm.put("\nTotal Memory ", (double) runtime.totalMemory()/(1024*1024));
        hm.put("\nFree Memory ", (double) runtime.freeMemory()/(1024*1024));
        hm.put("\nUsedup Memory ", (double) (runtime.totalMemory() - runtime.freeMemory())/(1024*1024));
        return hm.toString();
    }
}

DATATYPE = int时的输出1:

{
    Free Memory = 966.1398086547852, 
    Total Memory = 981.5, 
    Usedup Memory = 15.360191345214844}
{
    Free Memory = 869.7226409912109, 
    Total Memory = 981.5, 
    Usedup Memory = 111.77735900878906
}
DATATYPE = byte时

Output1:

{
    Free Memory = 966.1398086547852, 
    Total Memory = 981.5, 
    Usedup Memory = 15.360191345214844
}
{
    Free Memory = 765.0790710449219, 
    Total Memory = 981.5, 
    Usedup Memory = 216.42092895507812
}

我不知道我做错了什么。这可能是什么原因?

1 个答案:

答案 0 :(得分:1)

Byte是一个盒装基元,需要比原语(如int,double等)更多的内存。

诸如盒装基元(例如Byte,Integer,Double)之类的对象引用会产生额外的开销,例如Class引用。

因此,使用byte而不是Byte可以解决您的问题。