Library

Volume 3 · Python Deep Dive

Notebook
Sign in

Section 13

Memory Management & Performance (reference counting, generational GC, profiling tools, common optimizations)

818 words · about 4 min

13.1 CPython Memory Architecture

OS Virtual Memory → Python Memory Allocator → Arena (256KB) → Pool (4KB) → Block (8-512B)
Objects > 512 bytes bypass PyMalloc and go directly to C malloc.

PyMalloc manages small objects (≤512 bytes, in 8-byte increments across 64 size classes) extremely efficiently — this is why Python allocates/deallocates the countless small objects typical of Python programs quickly, at the cost of generally higher memory overhead than an equivalent C program.

13.2 Reference Counting

a = [1, 2, 3]
b = a           # refcount +1
c = [a, a]      # refcount +2 more

del b           # refcount -1
c.pop()         # refcount -1

Refcount increases on assignment, container insertion, argument passing, attribute assignment; decreases on del, scope exit, container removal/destruction, reassignment. Object is freed the instant refcount hits zero — deterministic, but cannot detect reference cycles (A → B → A) since neither object’s count ever reaches zero through mutual references alone.

13.3 Generational GC (Cycle Detection)

import gc
gc.get_threshold()   # (700, 10, 10) — Gen0 after 700 allocations, Gen1 after 10 Gen0 collections, etc.
gc.collect()         # Force a collection, returns count of unreachable objects found
gc.disable()         # Rare — benchmarks or manual cycle management only

Three generations, based on “most objects die young”: Gen0 collected most frequently, survivors promote to Gen1, then Gen2. This secondary collector specifically finds and breaks unreachable cycles that reference counting alone cannot free.

import weakref
class Cache:
    def __init__(self):
        self._cache = weakref.WeakValueDictionary()  # doesn't keep cached objects alive

weakref is the standard tool to break cycles deliberately (e.g., caches, observer callbacks, parent-child back-references) without relying on the cycle collector.

13.4 Memory Profiling

import sys, tracemalloc

sys.getsizeof(obj)          # SHALLOW size only — doesn't count referenced objects!

tracemalloc.start()
snapshot1 = tracemalloc.take_snapshot()
# ... code ...
snapshot2 = tracemalloc.take_snapshot()
for stat in snapshot2.compare_to(snapshot1, "lineno")[:10]:
    print(stat)   # Shows exactly which lines grew memory between snapshots

13.5 Optimization Techniques

# 1. Right data structure: set for membership instead of list — O(1) vs O(n)
# 2. "".join(strings) instead of += in a loop — O(n) vs O(n²)
# 3. __slots__ for millions of instances — ~60% memory reduction
# 4. Local variable caching — ~20% faster than repeated global/attribute lookups
def compute_fast(n):
    sqrt = math.sqrt   # local reference avoids repeated global lookup
    return [sqrt(i) for i in range(n)]
# 5. Generator expressions instead of list comprehensions when only iterating once
# 6. Built-ins (sum, min, max, sorted) — implemented in C, 5-10x faster than manual loops
# 7. NumPy for numeric work — releases the GIL, vectorized C operations

Profiling workflow: cProfile for function-level hotspots, timeit for micro-benchmark comparisons, tracemalloc for memory growth — always profile before optimizing; never guess.

Interview Q&A — Section 13

Q1: How does Python manage memory? Explain reference counting and garbage collection together.

A: Reference counting is the primary, deterministic mechanism — every object tracks how many references point to it, and memory is freed the instant that count reaches zero. Its weakness is reference cycles, which a secondary generational garbage collector handles: three generations based on the “most objects die young” heuristic, with Gen0 collected most often and survivors promoted upward. Layered underneath both is PyMalloc, which efficiently manages the huge number of small object allocations typical of Python code via arenas, pools, and fixed-size blocks.

Q2: How would you find and fix a memory leak in a Python application?

A: Confirm it with tracemalloc: take a snapshot, run the suspected code path repeatedly, force gc.collect(), take another snapshot, and use compare_to() to see which allocation sites are growing. Common root causes: unbounded caching (fix with lru_cache(maxsize=N) or weakref), circular references combined with __del__ (remove __del__, use context managers instead), ever-growing global collections (add eviction or use WeakSet/WeakValueDictionary), and unregistered event listeners holding strong references.

Q3: What’s the difference between sys.getsizeof() and an object’s actual memory footprint?

A: sys.getsizeof() measures only the shallow size of the container itself — for a list of dicts, it reports just the size of the array of pointers, not the dicts or strings those pointers reference. To get a true total you need a recursive deep-size calculation (walking dict/list/set/tuple contents while tracking visited object ids to avoid double-counting or infinite loops on cycles) or tracemalloc for empirically measured allocations.

Q4: Give a prioritized approach to optimizing a slow Python application.

A: Profile first with cProfile — never guess where time is spent. Then address in order of typical impact: fix the algorithm (wrong complexity class first — this dwarfs everything else), pick the right data structure (list→set for membership), use built-in functions over manual loops, use NumPy for numeric work, memoize expensive pure computations, use generators to cut memory, use __slots__ for high-instance-count classes, and only reach for concurrency or C extensions/Cython once the algorithmic and structural wins are exhausted.