I have a pretty basic question about storing data and its memory footprint.
I have a List<t>
that stores the base objects I need. The type t has an int id to define it, along with other fields.
I now have a Dictionary. If I create a Dictionary<t, int>
, where t is the object for the value, will the memory allocation be much higher that if I create a Dictionary<int, int>
, ie a copy of the t object is stored, or does only a refence to t get stored again?
Thanks
That depends on what T
is. If T
is a reference type (that is, a class
), then only a reference will be stored in the dictionary. If T
is a value type (a struct
), then a copy will be stored.
Reference types do not create duplicate objects as you pass them around. Under the covers, basically you are passing around pointers. So if you have N objects, you will have N x memory per object + the memory required to reference each object. This is regardless of the storage container for those references, in your case, a dictionary. You'll incur some memory cost for the dictionary, but if you created another dictionary and put all the same objects in it, you would only have 2x Dictionary memory costs plus one set of objects in memory. This is when you are using reference types.
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
Value types are always unique in memory. So if you create a dictionary of System.Int32 and then create a duplicate of the dictionary, you will have a copy of each value in the dictionary as well.
int myInt = 5; // one int created in memory
int myInt2 = myInt; // two ints have been created in memory
So let's figure out what memory chunks are allocated for certain scenarios:
// 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)
You're scenario:
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
Only a reference to your object gets stored. Memory allocation will be small.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With