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));
}
}
输出结果:
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());
}
}
运行结果:
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));
}
}
运行结果: