Profiling & Memory Optimization
Identify bottlenecks and optimize algorithm complexity.
Learning objectives
- Understand time vs space complexity trade-offs
- Use sys.getsizeof() to evaluate memory footprints
Lesson material
Generator Memory Footprint
List comprehensions create full objects in memory immediately, whereas generator expressions yield items on demand.
Example code
import sys
list_comp = [x for x in range(10000)]
gen_exp = (x for x in range(10000))
print("List size (bytes):", sys.getsizeof(list_comp) > 1000)
print("Generator size (bytes):", sys.getsizeof(gen_exp) < 300)
Practice exercise: Generator vs List
Create a generator expression `gen = (x * 2 for x in range(5))`. Print `sum(gen)`.
Test yourself with the Module 20: Performance & Profiling quiz →