空列表或字典使用了多少内存?如:
List<double> list = new List<double>();
Run Code Online (Sandbox Code Playgroud)
指针本身在x86和64位x64操作系统上至少占用32位,但是列表本身呢?有0条记录.
问的原因是,你可以通过设置列表来节省一些字节null吗?
(想象一下,你有一个类,其中包含一些List<T>在某些情况下正在使用的类,在其他情况下它不是,在这种情况下有一个boolean喜欢IsEmpty而null不是空列表可能会节省一些操作内存.特别是如果你有成千上万的这样的操作内存中的类,每一位都很重要.)
Ily*_*nov 19
由dotPeek反编译:
public class List<T> : IList<T>, ICollection<T>, IList, ICollection, IReadOnlyList<T>, IReadOnlyCollection<T>, IEnumerable<T>, 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
...
}
Run Code Online (Sandbox Code Playgroud)
你在x86上总共有20个字节(16个用于List<T>成员,4个用于元数据参考开销)和32个用于x64,包括对对象类型的响应,.net中的每个对象都有.这种计算大致不包括计数.
public class Dictionary<TKey, TValue> : ...
{
private int[] buckets; //4 bytes for x86, 8 for x64
private Dictionary<TKey, TValue>.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<TKey> comparer; //4 bytes for x86, 8 for x64
private Dictionary<TKey, TValue>.KeyCollection keys; //4 bytes for x86, 8 for x64
private Dictionary<TKey, TValue>.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
}
Run Code Online (Sandbox Code Playgroud)
x86 为44,x64 为72.再次粗略计算,因为需要不同对象的实例.