1

maven

        <!-- size of-->
        <dependency>
            <groupId>com.carrotsearch</groupId>
            <artifactId>java-sizeof</artifactId>
            <version>0.0.3</version>
        </dependency>

util

public class SizeOfUtil {

    public static enum SizeEnum {
        B {
            @Override
            public double getFromByteSize(long byteSize) {
                return byteSize;
            }
        },K {
            @Override
            public double getFromByteSize(long byteSize) {
                return byteSize*1.0/1024;
            }
        },M {
            @Override
            public double getFromByteSize(long byteSize) {
                return byteSize*1.0/1024/1024;
            }
        },G {
            @Override
            public double getFromByteSize(long byteSize) {
                return byteSize*1.0/1024/1024/1024;
            }
        };

        public abstract double getFromByteSize(long byteSize);
    }

    /**
     * 默认
     * 返回bytes
     * @param o
     * @return
     */
    public static double getObjectSize(Object o,SizeEnum sizeEnum){
        long byteSize = 0;
        if(o instanceof Collection<?>){
            byteSize = RamUsageEstimator.sizeOfAll(o);
        }else{
            byteSize = RamUsageEstimator.sizeOf(o);
        }
        return sizeEnum.getFromByteSize(byteSize);
    }
}

使用

System.out.println(SizeOfUtil.getObjectSize(map, SizeOfUtil.SizeEnum.K));

codecraft
11.9k 声望2k 粉丝

当一个代码的工匠回首往事时,不因虚度年华而悔恨,也不因碌碌无为而羞愧,这样,当他老的时候,可以很自豪告诉世人,我曾经将代码注入生命去打造互联网的浪潮之巅,那是个很疯狂的时代,我在一波波的浪潮上留下...