Skip to content

Instantly share code, notes, and snippets.

@zpoint
Last active February 25, 2023 08:21
Show Gist options
  • Save zpoint/5a9459aa35bff71748d61fc21b16a65c to your computer and use it in GitHub Desktop.
Save zpoint/5a9459aa35bff71748d61fc21b16a65c to your computer and use it in GitHub Desktop.
Lost connection to python doesn't means they will be deallocate

In Cpython

If you create some objects and lost connection to these object, it doesn't means the object will be deallocated

# python3.5
import psutil
import os
def memory_profile():
    print("The process consumes %.2f Megabytes\n" % 
    (psutil.Process(os.getpid()).memory_info().rss / float(1000 * 1000), ))

class A(object):
    def __init__(self):
        self.val = [[999999999999999999999999999.0 for _ in range(99999999)] for x in range(2)]
        self.left = None
        self.right = None
        
>>> memory_profile() # about 23.83M
>>> x = A()
>>> memory_profile() # about 1627.08M
>>> x = None
>>> memory_profile() # about 24.25M, reference count of instance object goes to 0
>>> x = A()
>>> y = A()
>>> x.right = y
>>> y.left = x
>>> memory_profile() # about 3228.97M
>>> x, y = None, None # now, I lost connection to these two instance
>>> # But these two instance connected to each other, each of them have a reference to the other, 
>>> # So the reference count never goes to zero, I can not deallocate them unless I terminate the process
>>> memory_profile() # about 3228.97M

So, If you build a giant net

A⇄B⇄C⇄D
⇅ ⇅ ⇅ ⇅          
E⇄F⇄G⇄H
.......

And you lost connection to the first column, The whole net will exists in your memory during the life time of the process.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment