JAVA如何计算对象在内存的大小

Java基本类型长度及对应对象的字节长度
基本类型 长度 the size of an object
Int      4    16
Short    2    16
Long    8     24
Byte     1     16
Character 1     16
Float    4     16
Double   8     24

在JDK1.8中可以采用ObjectSizeCalculator类来计算对象在内存中的大小

import java.sql.Timestamp;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import jdk.nashorn.internal.ir.debug.ObjectSizeCalculator;

public class Test {

    public static void main(String[] args) {

        System.out.println("Integer: " + ObjectSizeCalculator.getObjectSize(Integer.valueOf(122)));
        System.out.println("Long: " + ObjectSizeCalculator.getObjectSize(Long.valueOf(122L)));
        System.out.println("Double: " + ObjectSizeCalculator.getObjectSize(Double.valueOf(122.22)));
        System.out.println("Float: " + ObjectSizeCalculator.getObjectSize(Float.valueOf(122.22f)));
        System.out.println("Boolean: " + ObjectSizeCalculator.getObjectSize(Boolean.valueOf(false)));
        System.out.println("Character: " + ObjectSizeCalculator.getObjectSize(Character.valueOf('a')));
        System.out.println("Short: " + ObjectSizeCalculator.getObjectSize(Short.valueOf("1")));
        System.out.println("Byte: " + ObjectSizeCalculator.getObjectSize(Byte.valueOf("1")));
        System.out.println("Date: " + ObjectSizeCalculator.getObjectSize(new Date()));
        System.out.println("Timestamp: " + ObjectSizeCalculator.getObjectSize(new Timestamp(System.currentTimeMillis())));

        Map<String, Object> map = new HashMap<>();
        map.put("11", 11);
        map.put("22", "22");
        map.put("33", 33L);
        map.put("44", 44.44);

        System.out.println("Map: " + ObjectSizeCalculator.getObjectSize(map));

    }

}

运行结果:

Integer: 16
Long: 24
Double: 24
Float: 16
Boolean: 16
Character: 16
Short: 16
Byte: 16
Date: 24
Timestamp: 32
Map: 512

posted @ 2019-12-26 11:17  gaopengpy  阅读(3016)  评论(0编辑  收藏  举报