Thursday, July 8, 2021

python reference count

The Python getrefcount() is the function present inbuilt with the Python module sys. This functions takes Python object as an input and returns the number of references present for the given Python object.


import sys

print(sys.getrefcount(1556778))


The reference count is calculated based on the two factors…



Number of times object used in the bytecode

If the same object used earlier, number of object reference from earlier code  (can be in the same program or in a background process of Python)


When you pass the variable as a parameter to the function, reference count for the variable object is incremented. When the control goes out of the function, the reference count is decremented.


import sys

a =10

print(sys.getrefcount(a)) #17

 

def func(b):

    print(sys.getrefcount(a)) #19

 

func(a)

print(sys.getrefcount(a)) #17


Note: Reference count is shown as 19 instead of 18 because of variable ‘a’ is used two times in function- as a parameter to the function func(); as a parameter to the function sys.getrefcount().


When does the reference count increase?

  • while assigning operator
  • while passing the value as an argument to the function
  • appending object to the list



References:

https://www.csestack.org/python-getrefcount-reference-count-memory-management/#def


 

 

No comments:

Post a Comment