空的列表或字典的内存使用情况? [英] Memory usage of an empty List or Dictionary?
问题描述
一个空的列表或字典使用多少内存?如:
How much memory is used by an empty List or Dictionary? Such as:
List<double> list = new List<double>();
在x86和x64 OS的64位上,指针本身至少占用32位,但是列表本身呢?有0条记录.
The pointer itself eats at least 32 bits on x86 and 64 of x64 OS, but what about the list itself? With 0 records.
问的原因是,可以通过将列表设置为null
来节省一些字节吗?
The reason for asking is, can you save some bytes by setting lists to null
?
(假设您有一个包含某些List<T>
的类,在某些情况下正在使用该类,而在其他情况下则没有使用,在这种情况下,该类具有一个boolean
,如IsEmpty
和null
而不是空列表可能会节省一些操作内存.特别是在您将在操作内存中拥有数千个此类的情况下,每一位都很重要.
(Imagine you have a class that contains some List<T>
which in some cases is being used and in other case it is not, in that case having a boolean
like IsEmpty
and null
instead of empty list might save some operating memory. Especially in case you would have thousands of such classes in operating memory, every bit counts.)
推荐答案
由dotPeek编译:
Decompiled by 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
...
}
在x86上总共有 20 个字节(List<T>
成员有16个字节,元数据引用开销为4个字节),在x64上有 32 个字节,包括对类型的引用对象,.net中的每个对象都有.进行该计算时,大致不计算出鳄鱼数.
you got total of 20 bytes on x86 (16 for List<T>
members and 4 for metadata reference overhead) and 32 on x64, including reffernce to type of the object, which each object in .net have. This calculation is done roughly not counting alligment.
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
}
44 (对于x86)和 72 (对于x64).再次进行粗略计算,因为需要不同对象的实例.
44 for x86 and 72 for x64. Again rough calculation, since instances of different objects are required.
这篇关于空的列表或字典的内存使用情况?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!