Tuesday, July 13, 2021

Python Reference Counting

 In Python, all objects and data structures are stored in the private heap and are managed by Python Memory Manager internally. The goal of the memory manager is to ensure that enough space is available in the private heap for memory allocation. This is done by deallocating the objects that are not currently being referenced (used).


Reference counting is one of the memory management technique in which the objects are deallocated when there is no reference to them in a program. 


  • Using getrefcount from sys module
    In Python, by default, variables are passed by reference. Hence, when we run sys.getrefcount(var1 to get the reference count of var1, it creates another reference as to var1. So, keep in mind that it will always return one reference count extra. In this case, it will return 2.



  • Using c_long.from_address from ctypes module
    In this method, we pass the memory address of the variable. So, ctypes.c_long.from_address(id(var1)) returns the value 1 as there is only one reference to the same object in the memory.



Lets say 

var1 = [10,20]

var2 = var1, var3 = var1


In this case, rc1 = sys.getrefcount(var1) 

rc2 = ctypes.c_long.from_address(id(var1)).value

 

rc1 gives value of 4 and rc2 gives value of 3 



When var3 is set to None, then the ref count reduces to 2 


References:

https://towardsdatascience.com/understanding-reference-counting-in-python-3894b71b5611


No comments:

Post a Comment