Python Memory Optimisation -Slots

Prasad
2 min readNov 30, 2021

Slots Mechanism in Python reduces the memory usage with slots.But deliberate trade off with Flexibility.Regular python attribute stores the object in a dictionary.Regular object takes 64 bytes of space without assignment.Even empty object in python takes 64 bytes.

>>> a={}
>>> import sys
>>> sys.getsizeof(a)
64

If you have millions or thousand of objects , these may takes huge in gigabytes of memory.These may reduces the cpu caches of hold as cache stores less memory.

Techniques to Win performance with SLOTS

Lets calculate the size of a memory with some program.I am going to create a program that takes monthly expenditure.

class expenditure:

def __init__(self,income,food_exp,house_Rent) -> None:

self.income=income

self.food_exp=food_exp

self.house_Rent=house_Rent

import sys

cls=expenditure(100,1,2)

print(sys.getsizeof(cls.__dict__))

The output of program is 104.

Python is more dynamic program so the variable can added at the fly .

cls.travel_cost=200000

print(cls.__dict__) →{‘income’: 100, ‘food_exp’: 1, ‘house_Rent’: 2, ‘travel_cost’: 200000}

now the size increase to 168

To over come this “_Slots” comes in to existence.

class expenditure:

__slots__=[‘income’,’food_exp’,’house_Rent’]

def __init__(self,income,food_exp,house_Rent) -> None:

self.income=income

self.food_exp=food_exp

self.house_Rent=house_Rent

import sys

cls=expenditure(100,1,2)

print(sys.getsizeof(cls))

Now the memory size reduced to 56 bytes. The trade off on the performance tuning is that it will reduce the flexiblilty of adding variable on run time.

In really world _Slots usage is less but at the same time , if memory usage is high , slots will be only deal breaker.

Use wisely to enjoy the low level programing with high level languages.

--

--

Prasad

I am a OpenSource Enthusiast|Python Lover who attempts to find simple explanations for questions and share them with others