how to release used memory immediately in python list?

后端 未结 5 1667
佛祖请我去吃肉
佛祖请我去吃肉 2020-12-02 12:33

in many cases ,you are sure you definitely won\'t use the list again,i hope the memory should be release right now

a = [11,22,34,567,9999]
del a
5条回答
  •  一个人的身影
    2020-12-02 13:02

    Python uses Reference Count to manage its resource.

    import sys
    class foo:
        pass
    
    b = foo()
    a = [b, 1]
    
    sys.getrefcount(b)  # gives 3
    sys.getrefcount(a)  # gives 2
    
    a = None  # delete the list
    sys.getrefcount(b)  # gives 2
    

    In the above example, b's reference count will be incremented when you put it into a list, and as you can see, when you delete the list, the reference count of b get decremented too. So in your code

    def release_list(a):
       del a[:]
       del a
    

    was redundant.

    In summary, all you need to do is assigning the list into a None object or use del keyword to remove the list from the attributes dictionary. (a.k.a, to unbind the name from the actual object). For example,

    a = None # or
    del a
    

    When the reference count of an object goes to zero, python will free the memory for you. To make sure the object gets deleted, you have to make sure no other places reference the object by name, or by container.

    sys.getrefcount(b) # gives 2
    

    If sys.getrefcount gives you 2, that means you are the only one who had the reference of the object and when you do

    b = None
    

    it will get freed from the memory.

提交回复
热议问题