简体   繁体   中英

Python releasing memory of dictionary

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM