Slots Optimization in Python
Level 5349 keystrokes
This shows __slots__ for memory optimization. Slotted classes use less memory by avoiding instance __dict__ creation.
Python code
# RegularPoint is a normal class# Has __dict__ for storing attributes dynamically1class RegularPoint: # __init__ sets x and y coordinates # Creates entries in instance __dict__2 def __init__(self, x: int, y: int):3 self.x = x4 self.y = y5 # SlottedPoint uses __slots__ for optimization# No __dict__ is created, saving memory6class SlottedPoint: # __slots__ defines fixed set of attributes # Only x and y can be stored on instances7 __slots__ = ("x", "y")8 # __init__ sets same attributes as RegularPoint # But stores in slots instead of __dict__9 def __init__(self, x: int, y: int):10 self.x = x11 self.y = y12 # Import sys for memory size checking13import sys# Create instance of regular class14regular = RegularPoint(1, 2)# Create instance of slotted class15slotted = SlottedPoint(1, 2)16 # Show size of regular instance's __dict__# __dict__ takes extra memory for attribute storage17print(f"Regular: {sys.getsizeof(regular.__dict__)} bytes dict")# Slotted instances have no __dict__# Attributes stored directly in slots18print(f"Slotted has no __dict__")Output
Regular: 64 bytes dict Slotted has no __dict__
Practice typing this code. Results are not recorded in the rankings.
Symbols in this code
The symbols you type in this Python code and how often they appear.
_× 20:× 9"× 8(× 8)× 8,× 7=× 7.× 6{× 1}× 1