I understand that del d[key] will delete the key-value pair, whereas d[key]=None only de-references the value.
However, in terms of memory management, is there any difference? Does setting a value None trigger garbage collection immediately, assuming that there is no other variable referencing this value?
I ran a little experiment:
In [74]: import sys
In [75]: a = {'a': 'blah'}
In [76]: sys.getsizeof(a)
Out[76]: 280
In [77]: a['a'] = None
In [79]: sys.getsizeof(a)
Out[79]: 280
In [80]: del a['a']
In [81]: sys.getsizeof(a)
Out[81]: 280
Not sure if the approach is valid, but it seems no difference in terms of the size of the dictionary at all. I must miss something here.
sys.getsizeofmeasures the size of the dict itself; not the size of the values it contains.Noneis an object. It requires some memory.To find the size of a dict including the size of the values it contains, you could use pympler: