1.Java 1.8 API方式

import jdk.nashorn.internal.ir.debug.ObjectSizeCalculator;
import org.junit.jupiter.api.Test;

import java.util.HashMap;
import java.util.Map;

public class ObjectSizeTests {

    @Test
    public void testObjSize() {
        long lngValue = 10L;
        int intValue = 10;
        boolean boolValue = true;
        Map<String, String> map = new HashMap<>();
        map.put("key", "10");

        System.out.println(ObjectSizeCalculator.getObjectSize(lngValue));
        System.out.println(ObjectSizeCalculator.getObjectSize(intValue));
        System.out.println(ObjectSizeCalculator.getObjectSize(boolValue));
        System.out.println(ObjectSizeCalculator.getObjectSize(map));
    }
}

输出结果:
image.png
2.OpenJDK方式

<dependency>
    <groupId>org.openjdk.jol</groupId>
    <artifactId>jol-core</artifactId>
    <version>0.16</version>
</dependency>
import org.junit.jupiter.api.Test;
import org.openjdk.jol.info.ClassLayout;

import java.util.HashMap;
import java.util.Map;

public class ObjectSizeTests {

    @Test
    public void testObjSize() {
        long lngValue = 10L;
        int intValue = 10;
        boolean boolValue = true;
        Map<String, String> map = new HashMap<>();
        map.put("key", "10");

        System.out.println(ClassLayout.parseInstance(lngValue).toPrintable());
        System.out.println(ClassLayout.parseInstance(intValue).toPrintable());
        System.out.println(ClassLayout.parseInstance(boolValue).toPrintable());
        System.out.println(ClassLayout.parseInstance(map).toPrintable());
    }
}

运行结果:
image.png
3.Lucene依赖库方式

<dependency>
    <groupId>org.apache.lucene</groupId>
    <artifactId>lucene-core</artifactId>
    <version>4.0.0</version>
</dependency>
import org.apache.lucene.util.RamUsageEstimator;
import org.junit.jupiter.api.Test;

import java.util.HashMap;
import java.util.Map;

public class ObjectSizeTests {

    @Test
    public void testObjSize() {
        long lngValue = 10L;
        int intValue = 10;
        boolean boolValue = true;
        Map<String, String> map = new HashMap<>();
        map.put("key", "10");

        System.out.println(RamUsageEstimator.humanSizeOf(lngValue));
        System.out.println(RamUsageEstimator.humanSizeOf(intValue));
        System.out.println(RamUsageEstimator.humanSizeOf(boolValue));
        System.out.println(RamUsageEstimator.humanSizeOf(map));
    }
}

运行结果:
image.png

最后修改:2022 年 09 月 18 日
如果觉得我的文章对你有用,请随意赞赏