TreeMap<Long, Long> 集合需要多少内存?

How much memory takes TreeMap<Long, Long> collection granularly?

TreeMap<Long, Long> 包含 1000 个(所有唯一)键值对的集合需要多少内存?

是的,我只能看内存转储,但需要详细了解原因:

总计:X ?

JOL(Java 对象布局)

要回答此类问题,您可以使用工具 JOL

在你的情况下它会得到这样的结果:

java.util.TreeMap@17046283d footprint:
     COUNT       AVG       SUM   DESCRIPTION
      2000        24     48000   java.lang.Long
         1        48        48   java.util.TreeMap
      1000        40     40000   java.util.TreeMap$Entry
      3001               88048   (total)

Total 88048 bytes used

粒度

TreeMap 本身:

OFF  SZ                    TYPE DESCRIPTION               VALUE
  0   8                         (object header: mark)     N/A
  8   4                         (object header: class)    N/A
 12   4                  Set<K> AbstractMap.keySet        N/A
 16   4           Collection<V> AbstractMap.values        N/A
 20   4                     int TreeMap.size              N/A
 24   4                     int TreeMap.modCount          N/A
 28   4   Comparator<? super K> TreeMap.comparator        N/A
 32   4             Entry<K, V> TreeMap.root              N/A
 36   4                EntrySet TreeMap.entrySet          N/A
 40   4               KeySet<K> TreeMap.navigableKeySet   N/A
 44   4      NavigableMap<K, V> TreeMap.descendingMap     N/A
Instance size: 48 bytes

TreeMap.Entry

OFF  SZ          TYPE DESCRIPTION               VALUE
  0   8               (object header: mark)     N/A
  8   4               (object header: class)    N/A
 12   1       boolean Entry.color               N/A
 13   3               (alignment/padding gap)   
 16   4             K Entry.key                 N/A
 20   4             V Entry.value               N/A
 24   4   Entry<K, V> Entry.left                N/A
 28   4   Entry<K, V> Entry.right               N/A
 32   4   Entry<K, V> Entry.parent              N/A
 36   4               (object alignment gap)    
Instance size: 40 bytes

和龙:

OFF  SZ   TYPE DESCRIPTION               VALUE
  0   8        (object header: mark)     N/A
  8   4        (object header: class)    N/A
 12   4        (alignment/padding gap)   
 16   8   long Long.value                N/A
Instance size: 24 bytes

此外,您可能需要阅读有关 alignment and object header 的其他问题。