Memory Optimization Techniques
Optimize memory usage with generators, __slots__, efficient data structures, and garbage collection awareness.
15 min•By Priygop Team•Updated 2026
Memory Optimization
Memory Optimization
import sys
# 1. Use generators instead of lists
list_data = [x**2 for x in range(10000)]
gen_data = (x**2 for x in range(10000))
print(f"List: {sys.getsizeof(list_data)} bytes")
print(f"Generator: {sys.getsizeof(gen_data)} bytes")
# 2. Use __slots__ for memory-efficient classes
class PointRegular:
def __init__(self, x, y):
self.x = x
self.y = y
class PointSlots:
__slots__ = ['x', 'y']
def __init__(self, x, y):
self.x = x
self.y = y
p1 = PointRegular(1, 2)
p2 = PointSlots(1, 2)
print(f"\nRegular: {sys.getsizeof(p1.__dict__)} bytes (dict)")
print(f"Slots: no __dict__ (much smaller!)")
# 3. Use appropriate data types
import array
py_list = [1, 2, 3, 4, 5]
py_array = array.array('i', [1, 2, 3, 4, 5])
print(f"\nList: {sys.getsizeof(py_list)} bytes")
print(f"Array: {sys.getsizeof(py_array)} bytes")
# 4. Delete large objects when done
large_data = list(range(100000))
print(f"\nBefore del: {sys.getsizeof(large_data)} bytes")
del large_data
# large_data is now freed
# 5. Use itertools for memory-efficient iteration
from itertools import islice, chain
# Instead of creating full lists:
first_10 = list(islice(range(1000000), 10))
print(f"First 10 of million: {first_10}")
# Tips summary
print("\n=== Memory Tips ===")
tips = [
"Use generators for large sequences",
"Use __slots__ for many small objects",
"Delete large objects with 'del'",
"Use array.array for numeric data",
"Process files line-by-line, not all at once",
]
for tip in tips:
print(f" • {tip}")Tip
Tip
Use try/except for expected errors and assertions for things that should never happen. assert is for debugging, not input validation.
Diagram
Loading diagram…
Use Chrome DevTools Memory tab to detect leaks
Common Mistake
Warning
Using assert for input validation in production. Assertions can be disabled with python -O. Use if/raise for real validation.
Quick Quiz
Practice Task
Note
(1) Add assertions to verify preconditions. (2) Write defensive code with input validation. (3) Create custom exception hierarchy.