Lab 03: Memory Management

Objective

Understand CPython's memory model: reference counting, garbage collection, tracemalloc for leak detection, __slots__ memory savings, weak references for caches, and array/memoryview for zero-copy data.

Background

CPython manages memory with two layers: reference counting (objects are freed immediately when count hits 0) and a cyclic garbage collector (handles obj.self = obj cycles). Understanding both lets you write code that doesn't leak memory, uses memory efficiently, and avoids GC pauses.

Time

35 minutes

Prerequisites

  • Lab 01 (Metaprogramming)

Tools

  • Docker: zchencow/innozverse-python:latest


Lab Instructions

Step 1: Reference Counting & sys.getrefcount

💡 sys.getrefcount(x) returns count + 1 because the function call itself creates a temporary reference to x as its argument. Every variable assignment, list element, dict value, and function argument increments the refcount. When it hits zero, __del__ is called and memory is freed immediately — no GC needed for non-cyclic objects.

📸 Verified Output:


Step 2: tracemalloc — Memory Leak Detection

📸 Verified Output:


Steps 3–8: __slots__, weak references, memoryview, GC tuning, object pools, capstone

📸 Verified Output:


Summary

Technique
Memory impact
When to use

__slots__

−80% per instance

High-volume small objects

WeakValueDictionary

0 overhead

Caches that shouldn't block GC

array.array

Native C types, no boxing

Numeric arrays

memoryview

Zero-copy slicing

Large byte buffers

Generator

O(1) memory

Large datasets

Object pool

Avoid alloc/GC churn

Expensive-to-create objects

tracemalloc

Profiling only

Finding leaks

Further Reading

Last updated