Part 2 · 1 chapters · ~8 min

Memory Models: Manual, GC, Reference Counting, Ownership

Stack and heap allocation across languages, manual memory management, reference counting and cycles, tracing collectors (mark-sweep, copying, generational, concurrent), GC tuning knobs (GOGC, JVM heap and collector choice, V8 old space), Rust ownership and borrowing, arenas, and how memory model choice shapes latency.

3

Who frees, and what it costs

code
// Rust: ownership and borrowing checked at compile time
fn total(entries: &[Entry]) -> i64 { entries.iter().map(|e| e.amount).sum() }   // borrows, does not own
let entries = load();          // entries owns the Vec
let t = total(&entries);       // lend it out
drop(entries);                 // freed here (or at end of scope); any later use is a compile error

# Python: reference counting plus a cycle collector
import sys; x = []; sys.getrefcount(x)    # 2 (x, plus the argument)
a = {}; b = {'a': a}; a['b'] = b           # a cycle: refcounts never hit 0, gc module collects it

// Go: tracing, concurrent GC; one main knob
GOGC=200 ./server          # collect when heap grows 200% over live data: less CPU, more memory
GOMEMLIMIT=1GiB ./server   # soft memory limit (Go 1.19+): GC works harder near the limit
languagemodellatency character
C, C++manual (plus RAII in C++)predictable; bugs are memory-safety bugs
Rustownership (+ Rc/Arc when needed)predictable, no GC pauses
Swiftautomatic reference countingpredictable; retain/release overhead
Goconcurrent tracing GCsub-millisecond pauses typical; CPU cost
Javagenerational tracing (G1 default; ZGC for low pause)tunable; ZGC pauses under a millisecond
JavaScript (V8)generational (Scavenger + Mark-Compact)young-gen pauses short; old-gen work mostly concurrent
FOUR WAYS TO FREE MEMORY
who decides an object is dead
manualmalloc / free (C)reference countingSwift, Python (plus cycle collector), Rc in Rusttracing GCJVM, Go, V8, .NETownershipRust: freed at end of scope, checked at compile time
swipe the figure sideways, or tap expand for full screen
1/4
manual
The programmer frees memory. Fastest and most control; leaks, double frees and use-after-free are on you (C course P9).
you free itfast, unsafe