Thursday, 26 January 2017

GARBAGE COLLECTION IN PYTHON

The concept of removing the unused, unreferenced object from the memory location is known as a garbage collection. Once garbage collection is over memory will become free and rest of the program execution takes place in faster manner. There are two types of garbage collection supported by python. They are –

1. Automatic Garbage Collection – After starting execution of program periodically garbage collector program runs internally. Whenever garbage collector program is running, if any unused or unreferenced objects are available in memory location then it will remove those objects from memory location. Whenever any object is going to be removed from memory location then destructor of that class is going to be executed. In destructor we write the resource deallocation statement.

Example –
class A:
    a=
100
   
def __init__(self):
       
print 'in constructor'
   
def
__del__(self):
       
print 'in destructor'
A1=A()
A1=A()

Output –
in constructor
in constructor
in destructor
in destructor


2. Explicit Garbage Collection – The concept of executing the garbage collection program explicitly whenever we required is known as explicit garbage collection. By using ‘del’ keyword we can run garbage collector explicitly.

Example –
class A:
    a=
100
   
def __init__(self):
       
print 'in constructor'
   
def
__del__(self):
       
print 'in destructor'
A1=A()
del A1                               // explicit garbage

Output –
in constructor                // this line output from A1=A()
in destructor                  // this line output from del A1

Example –
class A:
    a=
100
   
def __init__(self):
       
print 'in constructor'
   
def
__del__(self):
       
print 'in destructor'
A1=A()
A2=A
A3=A
del A3
del A2
del A1

Output –
in constructor             // this line output from A1=A()
in destructor               // this line output from del A1

Note - Separate object is not created but the address of A1 is given to A2 or A3.

No comments:

Post a Comment