Ada*_*son 13
这取决于什么T.如果T是引用类型(即a class),则只有引用将存储在字典中.如果T是值类型(a struct),则将存储副本.
传递它们时,引用类型不会创建重复的对象.在封面下,基本上你是在传递指针.因此,如果您有N个对象,则每个对象将具有N x个内存+引用每个对象所需的内存.这与这些引用的存储容器无关,在您的情况下是字典.您将为字典带来一些内存成本,但如果您创建了另一个字典并将所有相同的对象放入其中,则内存中只有2x字典内存成本和一组对象.这是您使用引用类型时.
MyObject object = new MyObject(); // one object created in memory
MyObject object2 = object; // still only one object created in memory, but we have two references now
Run Code Online (Sandbox Code Playgroud)
值类型在内存中始终是唯一的.因此,如果您创建System.Int32的字典,然后创建字典的副本,您也将拥有字典中每个值的副本.
int myInt = 5; // one int created in memory
int myInt2 = myInt; // two ints have been created in memory
Run Code Online (Sandbox Code Playgroud)
因此,让我们弄清楚为某些场景分配了哪些内存块:
// two value types
Dictionary<int, int> myDictionary1 =
1 x Dictionary
N x int <key>
N x int <value>
Dictionary<int, int> myDictionary1 +
Dictionary<int,int> myDictionary2 (clone of 1) =
2 x Dictionary
2N x int <key>
2N x int <value>
// reference types
Dictionary <string, MyObject> myDictionary3 =
1 x Dictionary
N x string Reference
N x string instance (if they are all unique)
N x Object Reference
N x Object instance (if they are all unique)
Dictionary <string, MyObject> myDictionary3 +
Dictionary <string, MyObject> MyDictionary4 (clone of 3) =
2 x Dictionary
2N x string reference
1N x string instance (if they are all unique)
2N x Object reference
1N x Object instance (if they are all unqiue)
Run Code Online (Sandbox Code Playgroud)
你的情景:
Dictionary<int, MyObject> myDictionary5
1 X Dictionary
N X key
N X value reference
N X value object
Dictionary<int, MyObject> myDictionary5 +
Dictionary<int, MyObject> myDictionary6 (clone of 5) =
2 x Dictionary
2N x key
2N x value reference
1N x value objects
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
679 次 |
| 最近记录: |