What is the Garbage Collection in Python?

Garbage Collection is a process that deletes unnecessary objects automatically to free memory space. This process is called Garbage Collection. The name of Garbage Collection "gc". This process is helpful in memory management, the memory free by the garbage collection you can store other important data.

Python uses two strategies for memory allocation:
  • Reference Counting
  • Garbage collection

Reference Counting- The garbage collector is the simplest way to maintain a count for each object regarding how many times the object is referenced. When the object is referenced once, the referenced counting is 1. When the object is referenced twice, its reference count will be 2. when the object is zero referred the reference count of the object is 0. that means garbage collection will understand that the object is not used by the program, hence it can be deleted from the memory and memory will free.  
         A reference cycle is a cycle of references pointing to the first object from the last object.

A Reference Cycle

for example: Take four object A,B,C,D . Object A refers to object B. Object B refers to object C. Object C refers to object D. Object A, B, C, D are no longer used in the python program. Since the reference count for each object is 1 always so that the garbage collector can not remove the object from the memory. To solve these problems, the garbage collector uses an algorithm for detecting a reference cycle, and with the help of the algorithm removes the object from the reference cycle.

Garbage Collection-  Garbage collection is a scheduled activity. Garbage collection is based upon the threshold of object allocation or deallocation. python deletes the object which is not required, though this process is called garbage collection. The garbage collector runs automatically or manually. Automatically garbage collectors run automatically. if the allocated object and deallocated object value are higher than the threshold value the garbage collector invokes automatically. the automatic garbage collector work on two bases: time-based and event-based.

Post a Comment