I'm having a problem with releasing the memory of a dictionary in Python. I run the following check and followed the process memory usage:
a = dict()
for i in xrange(1000000):
a[i] = i
for i in xrange(1000000):
del a[i]
gc.collect()
the memory usage after running those lines is much higher than before. how can I release all of the memory? notice I don't want to delete the dict itself.
thanks.
Clear Memory in Python Using the del Statement Along with the gc. collect() method, the del statement can be quite useful to clear memory during Python's program execution. The del statement is used to delete the variable in Python.
The Python dictionary implementation consumes a surprisingly small amount of memory. But the space taken by the many int and (in particular) string objects, for reference counts, pre-calculated hash codes etc., is more than you'd think at first.
The dictionary is stored in memory in the form of a hash table with an ordered array of ranges and their corresponding values. The dictionary key has the UInt64 type. This storage method works the same way as hashed and allows using date/time (arbitrary numeric type) ranges in addition to the key.
Simply removing all the elements from the dictionary is not going to remove the dictionary from the memory. Python uses the reference counting technique. So, only when the reference count of an object drops to 0, it will be ready for garbage collection. So, your best bet would be to remove the reference a
from referring to the actual dictionary like this
a = None
if the dictionary has no other references, the dictionary referred by a
will be garbage collected automatically.
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