Reputation: 3211
Suppose I have 1000 different objects of the same class instantiated, and I assign it to a dictionary whose keys are integers from 1 to 1000, and whose values are those 1000 objects.
Now, I create another dictionary, whose keys are tuples (obj1, 1), (obj2,2), etc. The obj's being those same 1000 objects. And whose values are 1 to 1000.
Does the existence of those 2 dictionaries mean that memory usage will be doubled, because 1000 objects are in each dict's key and values?
They should NOT be, right? Because we are not creating new objects, we are merely assigning references to those same objects. So I can have 1000 similar dictionaries with those objects as either values or as keys (part of a tuple), and have no significant increases in memory usage.
Is that right?
Upvotes: 1
Views: 154
Reputation: 40904
Objects are not copied, but referenced.
If your objects are small (e.g. integers), the overhead of a list of tuples or a dict is significant.
If your objects are large (e.g. very long unique strings), the overhead is much less, compared to the size of the objects, so the memory usage will not increase much due to creation of another dict / list of the same objects.
Upvotes: 1