Cut Python memory footprints by 60% with __slots__, profile bottlenecks with cProfile, and tune garbage collection.
__slots__By default, every Python class instance stores its attributes in an internal dictionary (__dict__), consuming ~152 bytes per object.
Adding __slots__ tells CPython to store attributes in a fixed C-array without __dict__, shrinking object memory from 152 bytes to 48 bytes (68% savings)!
For pipelines handling 10M records in memory, this saves over 1 GB of RAM!
Pure Python for loops iterate through boxed PyObject pointers. Using NumPy or Polars invokes compiled C SIMD instructions that operate on 16 numbers in a single clock cycle.
for row in rows dict calculation with NumPy/PyArrow/Polars vectorized arrays speeds up execution 30x–100x by executing tight C/SIMD machine loops without GIL or PyObject boxing overhead.x in bad_ids_list scan O(N) per lookup; converting bad_ids to a set makes every lookup O(1) (turning 100M checks from hours into milliseconds!).out += chunk inside large loops—accumulate in a list and run "".join(chunks) once.Review the production code, company interview Q&As, incident traces, and comprehension quiz inside this lesson.
import sys
class HeavyRecord:
def __init__(self, record_id, amount, status):
self.record_id = record_id
self.amount = amount
self.status = status
class OptimizedRecord:
__slots__ = ('record_id', 'amount', 'status')
def __init__(self, record_id, amount, status):
self.record_id = record_id
self.amount = amount
self.status = status
heavy = HeavyRecord("REC-01", 100.50, "ACTIVE")
opt = OptimizedRecord("REC-01", 100.50, "ACTIVE")
print(f"Standard class size: {sys.getsizeof(heavy) + sys.getsizeof(heavy.__dict__)} bytes")
print(f"Optimized __slots__ size: {sys.getsizeof(opt)} bytes (Zero __dict__ overhead!)")
MemoryError: Unable to allocate 12.4 GiB for an array with shape...