多少内存吃空列表和字典
多少内存吃空列表和字典? 如:
List list = new List();
指针本身在x86和64位x64操作系统上至少占用32位,但是列表本身呢? 有0条记录。
编辑:因为有一些评论喜欢这里有什么意义:我想知道我是否可以通过更改列表来保存一些字节,我知道它们总是空为null
(想象你有一个类包含一些List
在某些情况下正在使用它,在其他情况下它不是,在这种情况下,它具有像IsEmpty这样的布尔值而null而不是空列表可能会节省一些操作内存。(特别是如果你在操作内存中有数千个这样的类,每一点都很重要))
由dotPeek反编译:
public class List : IList , ICollection , IList, ICollection, IReadOnlyList , IReadOnlyCollection , IEnumerable , IEnumerable { private T[] _items; //4 bytes for x86, 8 for x64 private int _size; //4 bytes private int _version; //4 bytes [NonSerialized] private object _syncRoot; //4 bytes for x86, 8 for x64 private static readonly T[] _emptyArray; //one per type private const int _defaultCapacity = 4; //one per type ... }
你在x86上总共有20个字节(16个用于List
成员,4个用于元数据参考开销)和32个用于x64,包括对对象类型的拒绝,.net中的每个对象都有。 这种计算大致不包括计数。
public class Dictionary : ... { private int[] buckets; //4 bytes for x86, 8 for x64 private Dictionary.Entry[] entries; //4 bytes for x86, 8 for x64 private int count; //4 bytes private int version; //4 bytes private int freeList; //4 bytes private int freeCount; //4 bytes private IEqualityComparer comparer; //4 bytes for x86, 8 for x64 private Dictionary.KeyCollection keys; //4 bytes for x86, 8 for x64 private Dictionary.ValueCollection values; //4 bytes for x86, 8 for x64 private object _syncRoot; //4 bytes for x86, 8 for x64 private const string VersionName = "Version"; //one per type private const string HashSizeName = "HashSize"; //one per type private const string KeyValuePairsName = "KeyValuePairs"; //one per type private const string ComparerName = "Comparer"; //one per type }
x86为44 ,x64为72 。 再次粗略计算,因为需要不同对象的实例。