Java查看变量内存中的大小
导入Maven依赖
<dependency> <groupId>com.carrotsearch</groupId> <artifactId>java-sizeof</artifactId> <version>0.0.5</version> </dependency>
调用类 RamUsageEstimator 的 sizeOf 方法
int[] arr = { 1, 2, 3}; /** Returns the size in bytes of the int[] object. */ long size = RamUsageEstimator.sizeOf(arr); System.out.println(size); // 32
返回long型的byte大小。 该类中,除了 sizeOf 方法,还有 shallowSizeOf(Object) 方法,该大小是变量所有属性的大小,如果是引用变量的话,不包括引用变量指向的变量在堆内存的大小,仅仅计算引用变量本身的byte。 举个例子
int[] arr = { 1, 2, 3}; long size = RamUsageEstimator.sizeOf(arr); System.out.println(size); // 32 System.out.println(RamUsageEstimator.shallowSizeOf(arr)); // 32 System.out.println(RamUsageEstimator.sizeOf("中")); // 48 String[] arr2 = { "中", "国"}; System.out.println(RamUsageEstimator.sizeOf(arr2)); // 120 /** * Estimates a "shallow" memory usage of the given object. For arrays, this will be the * memory taken by array storage (no subreferences will be followed). For objects, this * will be the memory taken by the fields. * * JVM object alignments are also applied. */ System.out.println(RamUsageEstimator.shallowSizeOf(arr2)); // 24
对于int[]数组2个方法结果一致,因为int是基本数据类型没有引用。 对于String[]数组,保存的只是引用的常量池中的地址,所以 shallowSizeOf() 得到结果小。
下一篇:
挺进大厂,一下干了 6个 offer