An Interest In:
Web News this Week
- March 22, 2024
- March 21, 2024
- March 20, 2024
- March 19, 2024
- March 18, 2024
- March 17, 2024
- March 16, 2024
Consume 50% less memory with your Python objects
By default, in Python, objects have a dict attribute.
It's a dictionary used to access the object variables per key.
It is useful to allow dynamic variables' creation.
However this flexibility can lead to creation of new object variables, when misspelled. Python will create a new variable with the given name.
With slots, we can specifically declare data variables.
Then Python will allocate space for them in memory and skip the creation of the dict attribute.
It also forbids the creation of any object's variable which are not declared in the slots attribute.
By using slots, you also decrease the memory used by your class instances.
Slots can also be used in dataclasses if you're using python3.10 or higher. Simply add slots=True
to the decorator.
It makes a huge difference if you're creating lots of objects!
from dataclasses import dataclass# https://pypi.org/project/Pympler/from pympler.asizeof import asizeof# Dataclass with slots@dataclass(frozen=True, slots=True)class SmallObjectWithDataclass: first_name: str last_name: str# Class with slotsclass SmallObject: __slots__ = ["first_name", "last_name"] def __init__(self, first_name, last_name) -> None: self.first_name: str = first_name self.last_name: str = last_name# Class with no slotsclass BiggerObject: def __init__(self, first_name, last_name) -> None: self.first_name: str = first_name self.last_name: str = last_namep = SmallObjectWithDataclass("Jerome", "K")print(asizeof(p)) # Output: 160 Bytesp2 = SmallObject("Jerome", "K")print(asizeof(p2)) # Output: 160 Bytesp3 = BiggerObject("Jerome", "K")print(asizeof(p3)) # Output: 392 Bytes
Hope this helps and have a great Day
Jerome
Original Link: https://dev.to/jeromek13/consume-50-less-memory-with-your-python-objects-3ie6
Dev To
An online community for sharing and discovering great ideas, having debates, and making friendsMore About this Source Visit Dev To