要查看一个 map 的内存大小,可以使用 Java 的 Instrumentation API 或者使用 Apache Commons Lang 库中的 SizeOf 工具类。

方法一:使用 Instrumentation API

import java.lang.instrument.Instrumentation;
import java.util.HashMap;
import java.util.Map;

public class MapSizeTest {
    public static void main(String[] args) {
        Map<String, String> map = new HashMap<>();
        map.put("key1", "value1");
        map.put("key2", "value2");

        Instrumentation instrumentation = java.lang.management.ManagementFactory.getPlatformMBeanServer().getMBean(Instrumentation.class);
        long size = instrumentation.getObjectSize(map);
        System.out.println("Map size: " + size + " bytes");
    }
}

方法二:使用 Apache Commons Lang 库

import org.apache.commons.lang3.SerializationUtils;
import java.util.HashMap;
import java.util.Map;

public class MapSizeTest {
    public static void main(String[] args) {
        Map<String, String> map = new HashMap<>();
        map.put("key1", "value1");
        map.put("key2", "value2");

        int size = SerializationUtils.serialize(map).length;
        System.out.println("Map size: " + size + " bytes");
    }
}

注意:这些方法只能估计 map 占用的内存大小,并不是精确的值

java 如何查看一个 map 的内存大小

原文地址: http://www.cveoy.top/t/topic/iHcr 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录