Python Memory Management - Memory Allocation And Garbage Collection

Python Memory Management - Memory Allocation And Garbage Collection

In python everything is considered as an object. In python we do not have variables instead python has names. When we declare a name/variable in python it stores the name in the memory. Every python name/variable points to its reference in the memory and reference points to the object.

Let's consider the example code "a = 100" , "a" is name and it's points to the reference "31365024" and the reference points to the object "100" which is in binary format. A name is just a label for an object. In python each object can have lots of names.

Python has stack memory and heap memory. Stack memory stores the state of the program. Private heap memory stores the objects and data structures. Python memory manager will takes care of the allocation of the private heap memory to the names/variables. Python manager uses the concept called Reference counting, whenever a new object is created it will update the reference count of the object.

case1

a = 100  
b = 200  

case2

a = 100  
b = 100

Lets consider the above code.

In "case1" python memory manager will create the two objects. "a" points to the object "100" and "b" points to the object "200". The reference count of the object "100" is 1 and the reference count of the object "200" is 1.

In "case2" python memory manager creates only one object i.e "100" and reference count is "2". Whenever a new object is created pyhon manager will checks the memory for the object. If object already exists python manager will not create new object instead it references the name to the object and increases the reference counter of the object.

Every python object holds three things

  1. object type
  2. object value
  3. object reference counter

Memory table for "case2"

type int
value 100
reference count 2
references a, b

We can get the object memory location with python built-in function "id"

a = 100
print(id(a))
# 10914336
b = 100
print(id(b))
# 10914336
print(id(a) == id(b))
# True

try the above code in python interpreter to confirm yourself.

Garbage collection in python

Garbage collection is the process of removing the unused variables/names and freeing the memory.

In python garbage collection is performed based on the reference count mechanism. Whenever the object is created the python will increases the reference count of the object by one. Whenever the reference is removed then it decreases the reference count by one. Garbage collector periodically checks and removes the objects from memory whose reference count is zero.

a = 100
b = 100
# reference count of object 100 is 2
del a
# reference count of object 100 is 1
del b
# reference count of object 100 is 0
# So, garbage collector will remove the object 100 from the memory.