Garbage collector in python

kibrahimsha4 300 views 11 slides Mar 01, 2021
Slide 1
Slide 1 of 11
Slide 1
1
Slide 2
2
Slide 3
3
Slide 4
4
Slide 5
5
Slide 6
6
Slide 7
7
Slide 8
8
Slide 9
9
Slide 10
10
Slide 11
11

About This Presentation

These slides explain the implementation of the Python core object, memory reference, reference counter, and garbage collector in python.


Slide Content

Garbage Collector(GC)
in Python

About Me
★Working in python, django, js > 6years
★Github: github.com/ibrahimsha23
★Linkedin: in/ibrahimshak

GC Definition
Definition(wiki)
●garbage collection (GC) is a form of automatic memory management. The
garbage collector, or just collector, attempts to reclaim garbage, or memory
occupied by objects that are no longer in use by the program.

Purpose:
●Freed the memory block of unwanted objects in python.

Prerequisites of GC
To know the gc module implementation in CPython, we need to understand few
elements,
➢Pyobj (Python Core Object)
➢Memory reference
➢Reference counter

Pyobj
●Pyobj is the python core object.
●All objects in python, finally referred as pyobj.
●Pyobj has three properties,
○Type
○Value
○Reference Counter
● If you inspect any object in python will have these properties.

Memory Reference


●In python, Everything is an object.
●Tag reference.
●Creating new object with same value, will not create a new malloc.
○ a=5, b=5
○ a = 6
●Refer: Link

Reference Counter


●On every allocation/ tag the memory reference of an object, will increase the ref count for the
object.
●On every assignment, function call args reference count will be increased.
●On de-allocation of object, will decrease the reference count.
●When ref count leads to zero, will be removed from the memory block.
●Reference counter is one of the types of GC.
●`sys.getrefcount( )`
●Refer: Link

Drawbacks of Ref counter
●Cyclic reference:
○Self reference objects
○Count will never decrease to zero.
○ It always be a unused objects.
<python>
a = [5]
a.append(a)
</python>
●‘Del’ keyword in python.
●Refer: Link

GC - Implementation
●Generational based garbage collection
○{0, 1, 2}
●Solving cyclic reference issue.
●Enabling/Disabling garbage collection manually.
●Source: Modules/gcmodule.c
●Refer: Link

●Gen -0 -> Newly created objects
●Gen - 1 -> Live objects
●Gen -2 -> Global objects

MISC (GC)

●Pypy, jython, iron python implementation on gc.
●Instagram disabling gc.(link).

Queries?