Memory Management in Python


Writing a memory-efficient and a code that executes quickly is what every developer wants while working on any programming language. In Python, memory allocation and deallocation is not manual, since Python has a Garbage Collector.

Now, what is a Garbage Collector.

Garbage Collector

Garbage Collection is how the memory is freed when not use and how it can be made available for other objects. Python deletes the objects that are no longer in use. This is what we call Garbage Collection. The garbage collector initiates its execution with the program and is activated if the reference count drops to zero.

Python's garbage collector runs during program execution and is triggered when an object's reference count reaches zero. An object's reference count changes as the number of aliases that point to it changes.

Let us now see how memory is allocated in Python −

Static Memory Allocation – Stack

In static memory allocation, the memory is allocated at the compile time. The Stack data structure stores the static memory.

A quick example where the memory allocates on stack −

static int x=2;

Dynamic Memory Allocation – Heap

In dynamic memory allocation, the memory is allocated at the run time. The Heap stores the dynamic memory. It frees up the memory space if the object is no longer needed.

A quick example where the memory allocates on heap for 2 integers −

x = [0]*2

As we discussed above, the garbage collector initiates its execution with the program and is activated if the reference count drops to zero. Let’s see what is a reference count.

Reference Count

The Python garbage collector initiates its execution with the program and is activated if the reference count drops to zero. Let us see when the reference count increase or decreases

The reference count value increase when −

  • When a new name is assigned or in a dictionary or tuple, the reference count increases its value.

  • If we reassign the reference to an object, the reference counts decrease its value.

The reference count value decreases when −

  • The value decreases when the object's reference goes out of scope.
  • The value decreases when an object is deleted.

Therefore, reference counting is actually how many times other objects reference an object. With that, The de-allocation occurs when the reference count drops to zero.

Updated on: 19-Sep-2022

782 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements