2013-04-21 26 views
3

多少內存吃空列表和字典?如:多少內存吃空列表和字典

List<double> list = new List<double>(); 

指針本身吃在x86有關列表本身至少32位和64位操作系統的64,但什麼?有0條記錄。

編輯:因爲有喜歡在這點一些意見:我想知道我是否可以通過改變名單,我知道他們會一直空null(想象你有一個包含一類節省一些字節一些List<T>在某些情況下正在使用,而在其他情況下它不是,在這種情況下有一個像IsEmpty這樣的布爾值,並且null而不是空列表可能會節省一些操作內存(特別是在您將有數千個這樣的類正在運行內存,通過反編譯dotPeek每一個位計數))

+0

我認爲你最好的選擇是使用像ANTS這樣的內存分析器,並查找這些特定對象及其內存使用情況。 – Kippie 2013-04-21 13:34:35

+0

我沒有錢螞蟻和自動取款機我在ubuntu – Petr 2013-04-21 13:35:41

+5

我認爲在幾乎所有情況下,答案是「這麼小,它並不重要」。 – svick 2013-04-21 13:55:31

回答

14

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 字節(16 List<T>成員和4元數據參考開銷)和在x64 ,包括reffernce到類型的對象,該對象在.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 
} 

x86和針對x64。再次粗略計算,因爲需要不同對象的實例。

+0

虛擬方法表怎麼樣? – 2013-04-21 13:41:04

+0

@PieterGeerkens是不是每個類型創建一個? 'List '也有兩個靜態變量,但我沒有對它們進行計數,因爲它們不會影響對象本身的大小。據我記得,.net中的每個對象只有一個參考開銷。 – 2013-04-21 13:42:42

+0

除了測量死代碼的代價外,我無法看到任何問題,所以這意味着計算一切。這是一個使用鏈接(標題爲「DOT NET中枚舉的成本」,由Joe Duffy提供):http://www.bluebytesoftware.com/blog/2008/09/21/TheCostOfEnumeratingInNET.aspx – 2013-04-21 13:49:06