SyntaxPilot
Courses/Go Programming/Lesson 56
Video coming soonThis lesson’s video is being made

Start with the notes below; the video appears here as soon as it is on YouTube.

Go Programming · Lesson 56 of 89

The garbage collector

garbage collectiontri-colour concurrent mark and sweepwrite barriersGC pacerGOGCGOMEMLIMITstop-the-world pausesGODEBUG=gctrace=1runtime.ReadMemStatsruntime.GCfinalizersruntime.AddCleanup (Go 1.24)weak pointers (weak package)heap size vs live heap

These are the notes for Go episode 56. Episode 55 showed that some values escape to the heap. Somebody has to free that memory again. In C you do it yourself with free, and get memory leaks, dangling pointers and double frees. Go has no free at all: a garbage collector (GC) finds heap memory the program can no longer reach and frees it. We invent it twice, first by counting references (which can't free a cycle) and then by tracing from the roots with mark and sweep and tri-colour marking. We see why marking while the program runs needs a write barrier, read a real GODEBUG=gctrace=1 trace, tune the pacer with GOGC and set a ceiling with GOMEMLIMIT, and finish with finalizers vs runtime.AddCleanup and weak pointers.

All outputs here are from real runs (Go 1.24.7, linux/amd64, a machine with 2 CPUs). GC counts and heap sizes change a little from run to run, because the collector runs at the same time as the program.

Facts and sources

  • Go 1.24.7 runtime package documentation (extern.go): "The GOGC variable sets the initial garbage collection target percentage ... The default is GOGC=100. Setting GOGC=off disables the garbage collector entirely." "The GOMEMLIMIT variable sets a soft memory limit for the runtime." The gctrace=1 line format and its phases: "stop-the-world (STW) sweep termination, concurrent mark and scan, and STW mark termination".
  • Go 1.24.7 runtime/mgc.go: the collector "is a concurrent mark and sweep that uses a write barrier"; it drains "the work queue of grey objects, scanning each grey object to black".
  • A Guide to the Go Garbage Collector: the target heap formula Live heap + (Live heap + GC roots) × GOGC / 100; "doubling GOGC will double heap memory overheads and roughly halve GC CPU cost"; GOMEMLIMIT was added "in the 1.19 release"; the limit is soft; the GC's CPU use under the limit is capped at "roughly 50%"; the GC "takes 25% of CPU resources when in the mark phase"; Go has a non-moving GC; "Prefer cleanups to finalizers".
  • Go 1.25 release notes: Green Tea GC as an experiment; AddCleanup cleanups now run concurrently and in parallel.
  • Go 1.26 release notes: "The Green Tea garbage collector ... is now enabled by default"; "we expect somewhere between a 10–40% reduction in garbage collection overhead in real-world programs that heavily use the garbage collector"; opt out with GOEXPERIMENT=nogreenteagc.

The problem: freeing memory by hand

In Raju's storeroom Freeing memory by hand (C)
nobody throws old boxes out: the room fills up memory leak: memory no longer needed is never given back, so the program keeps growing
a box thrown out while a cook still uses it dangling pointer / use after free: a pointer to memory that was freed and may be reused
two helpers throw out the same box double free: the same memory freed twice, which can corrupt the allocator (the code that hands out memory)

Trying free in Go

package main

import "fmt"

type Bill struct {
    Table int
    Items [1000]int
}

func main() {
    for i := 1; i <= 3; i++ {
        b := &Bill{Table: i}
        fmt.Println("served table", b.Table)
        free(b) // in C you'd call free(b) here
    }
}

Real output:

# command-line-arguments
./main.go:14:9: undefined: free

Go has no free. You can't free memory too early or twice. The runtime frees memory that nothing can reach: that's the garbage collector. Garbage = heap memory the program can never reach again.

Idea 1: reference counting, and why it fails

  • Reference counting: every object keeps a counter of how many pointers point at it; copy a pointer, +1; drop one, −1; at 0, free the object at once.
  • Cycle: objects that point at each other in a ring, e.g. two joined tables: a.Partner = b; b.Partner = a.
  • When the program drops a and b, each still has one pointer to it (from the other). The counts never reach 0: a cycle leaks. Go does not use reference counting.

Idea 2: trace from the roots — mark and sweep

  • Roots: the places the program reads directly — global (package-level) variables and the local variables on every goroutine's stack.
  • Reachable (live): an object you can get to by following pointers from a root. Only reachable memory can ever be used again.
  • Tri-colour marking:
  • white: not seen yet (at the start, every heap object);
  • grey: reachable, but its pointers haven't been looked at yet (the to-do list);
  • black: reachable and fully scanned. 1. Everything the roots point to turns grey. 2. Take a grey object, colour its children grey, colour it black. 3. Repeat until nothing is grey.
  • Mark phase: steps 1–3. Sweep phase: walk the heap and make all still-white memory free to reuse.
  • Cycles are no problem: an unreachable cycle stays white and is swept.
ROOTS                    HEAP
global: live  ───────▶  open orders ──▶ order 7 ──▶ bill 7      (black: reachable)
main's stack: p ─────▶  printing bill                            (black)
                        old bill ⇄ old receipt                   (white: garbage, swept)

Concurrent marking and the write barrier

  • Stop the world (STW): pause every goroutine while the GC works. Simple, but every request waits.
  • Concurrent: at the same time as your program runs. Go marks concurrently; during marking the GC uses about 25% of the CPU.
  • The danger: while marking, your code moves pointers. Black A (already scanned) takes a pointer to white C, and grey B, the only other path to C, drops it. The marker never re-scans A, so C stays white and would be freed while A uses it.
  • Write barrier: while marking is on, every pointer write also runs a tiny piece of extra code (added by the compiler) that shades the target grey. C turns grey and is scanned. The Go runtime's own description: "a concurrent mark and sweep that uses a write barrier".
  • Two short STW pauses remain: at the start (sweep termination) and the end (mark termination) of each cycle.
  • Go's GC is non-moving: objects are never moved, so pointers stay valid.

Watching the GC: GODEBUG=gctrace=1

GODEBUG is an environment variable that switches on runtime debug settings; gctrace=1 prints one line per GC cycle to standard error.

// $ go build -o app .
// $ GODEBUG=gctrace=1 ./app
// ---- main.go ----
package main

import "fmt"

var live [][]byte

func main() {
    for i := 0; i < 40; i++ {
        live = append(live, make([]byte, 100_000)) // 4 MB still in use
    }
    for i := 0; i < 150; i++ {
        bill := make([]byte, 100_000) // 15 MB of short-lived garbage
        bill[0] = byte(i)
    }
    fmt.Println("done, open orders:", len(live))
}

Real output (standard output, then the trace on standard error):

done, open orders: 40

gc 1 @0.000s 7%: 0.010+0.29+0.007 ms clock, 0.021+0.069/0.057/0.10+0.015 ms cpu, 3->4->4 MB, 4 MB goal, 0 MB stacks, 0 MB globals, 2 P
gc 2 @0.001s 9%: 0.053+0.26+0.003 ms clock, 0.10+0.039/0.095/0+0.006 ms cpu, 7->9->6 MB, 8 MB goal, 0 MB stacks, 0 MB globals, 2 P
gc 3 @0.004s 6%: 0.011+0.21+0.063 ms clock, 0.022+0.034/0.043/0+0.12 ms cpu, 11->12->5 MB, 13 MB goal, 0 MB stacks, 0 MB globals, 2 P
Field Meaning
gc 3 the GC cycle number
@0.004s time since the program started
6% share of time spent in GC since the start
0.011+0.21+0.063 ms clock wall-clock time of STW sweep termination + concurrent mark + STW mark termination
... ms cpu CPU time of the phases (mark split into assist / background / idle)
11->12->5 MB heap at cycle start → heap at cycle end → live heap (reachable after marking)
13 MB goal the heap size the pacer aimed for
2 P processors used (GOMAXPROCS)

The pauses are fractions of a millisecond; the live heap stays near the 4 MB of open orders.

The pacer and GOGC

  • Run the GC too often → CPU wasted on marking. Too rarely → memory piles up.
  • The pacer is the part of the runtime that picks when the next cycle should finish. The heap goal:

goal ≈ live heap + (live heap + GC roots) × GOGC / 100

  • GOGC (environment variable, default 100): how much the heap may grow, in percent of the live heap, before the next cycle. 4 MB live, GOGC=100 → about 8 MB goal.
  • "Doubling GOGC will double heap memory overheads and roughly halve GC CPU cost" (GC guide).
  • GOGC=off turns the collector off (unless a memory limit applies).
// $ go build -o app .
// $ GOGC=100 ./app
// $ GOGC=50 ./app
// $ GOGC=400 ./app
// $ GOGC=off ./app
// ---- main.go ----
package main

import (
    "fmt"
    "runtime"
)

var live [][]byte // the orders still open: about 4 MB, always reachable

func main() {
    for i := 0; i < 40; i++ {
        live = append(live, make([]byte, 100_000))
    }
    for i := 0; i < 2000; i++ { // 2000 short-lived bills of 100 KB = 200 MB of garbage
        bill := make([]byte, 100_000)
        bill[0] = byte(i)
    }
    var m runtime.MemStats
    runtime.ReadMemStats(&m)
    fmt.Printf("GC cycles: %3d   heap now: %3d MB   total allocated: %d MB\n",
        m.NumGC, m.HeapAlloc>>20, m.TotalAlloc>>20)
}

Real output (three runs gave 47, 27 and 47 cycles for GOGC=100):

$ go build -o app .
$ GOGC=100 ./app
GC cycles:  45   heap now:   6 MB   total allocated: 207 MB
$ GOGC=50 ./app
GC cycles:  98   heap now:   4 MB   total allocated: 207 MB
$ GOGC=400 ./app
GC cycles:  11   heap now:  20 MB   total allocated: 207 MB
$ GOGC=off ./app
GC cycles:   0   heap now: 207 MB   total allocated: 207 MB
  • runtime.ReadMemStats(&m) fills a runtime.MemStats with the runtime's memory numbers: NumGC (cycles so far), HeapAlloc (heap bytes in use now, including garbage not yet swept), TotalAlloc (all bytes ever allocated), HeapSys (heap memory obtained from the OS).

GOMEMLIMIT: a soft ceiling

  • Containers have a memory limit; going over it gets the program killed: out of memory (OOM).
  • GOGC only looks at growth. Since Go 1.19, GOMEMLIMIT sets a soft memory limit for the whole Go runtime (heap and other runtime memory). Suffixes B, KiB, MiB, GiB, TiB; a mebibyte (MiB) is 1024 × 1024 bytes.
  • Soft: if live data really needs more, Go goes over rather than crash. To avoid thrashing (constant GC cycles), GC CPU under the limit is capped at roughly 50%.
// $ go build -o app .
// $ GOGC=off ./app
// $ GOGC=off GOMEMLIMIT=16MiB ./app
// (same main.go as above)

Real output:

$ go build -o app .
$ GOGC=off ./app
GC cycles:   0   heap now: 207 MB   total allocated: 207 MB
$ GOGC=off GOMEMLIMIT=16MiB ./app
GC cycles:  33   heap now:  10 MB   total allocated: 207 MB

A common container setup: GOMEMLIMIT a little below the container limit, GOGC left at 100.

Controlling the GC from code

var m runtime.MemStats
runtime.ReadMemStats(&m)        // NumGC, HeapAlloc, TotalAlloc, HeapSys ...
runtime.GC()                    // run a full cycle now and wait for it
debug.SetGCPercent(200)         // = GOGC, at run time (runtime/debug)
debug.SetMemoryLimit(64 << 20)  // = GOMEMLIMIT, 64 MiB

runtime.GC() is for demos and tests; in a server, let the pacer decide.

Finalizers vs runtime.AddCleanup

  • Finalizer: runtime.SetFinalizer(obj, f) — f(obj) runs some time after the GC finds obj unreachable.
  • Cleanup (Go 1.24+): runtime.AddCleanup(obj, f, arg) — f(arg) runs after obj is unreachable. arg must not be obj itself.
package main

import (
    "fmt"
    "runtime"
    "time"
)

type Table struct {
    No      int
    Partner *Table // two tables joined for a big family
}

func main() {
    a, b := &Table{No: 1}, &Table{No: 2}
    a.Partner, b.Partner = b, a // a cycle: a -> b -> a
    runtime.SetFinalizer(a, func(t *Table) { fmt.Println("finalizer: table", t.No) })
    runtime.SetFinalizer(b, func(t *Table) { fmt.Println("finalizer: table", t.No) })

    c, d := &Table{No: 3}, &Table{No: 4}
    c.Partner, d.Partner = d, c // the same cycle
    runtime.AddCleanup(c, func(no int) { fmt.Println("cleanup: table", no) }, c.No)
    runtime.AddCleanup(d, func(no int) { fmt.Println("cleanup: table", no) }, d.No)

    a, b, c, d = nil, nil, nil, nil // nobody can reach any table now
    runtime.GC()
    time.Sleep(50 * time.Millisecond) // they run on their own goroutine
    runtime.GC()
    time.Sleep(50 * time.Millisecond)
    fmt.Println("end of main")
}

Real output:

cleanup: table 4
cleanup: table 3
end of main

The finalizers never run: a finalizer receives the object and could resurrect it (make it reachable again), so everything the object points to must stay alive until it runs; in a cycle each keeps the other alive forever. A cleanup gets only a plain value, so the cycle is freed. "Prefer cleanups to finalizers." Never rely on either for work that must happen (closing files, saving data): use defer.

Weak pointers

  • A normal (strong) pointer keeps its object alive. A map used as a cache keeps every entry alive: a leak.
  • The weak package (Go 1.24): weak.Make(p) returns a weak.Pointer[T], a weak pointer that does not keep the object alive. .Value() returns the pointer, or nil once the GC freed the object.
package main

import (
    "fmt"
    "runtime"
    "weak"
)

type Photo struct {
    Name   string
    Pixels [1 << 20]byte // 1 MB
}

var cache = map[string]weak.Pointer[Photo]{} // a cache that doesn't keep photos alive

func load(name string) *Photo {
    if p := cache[name].Value(); p != nil {
        return p // still in memory: reuse it
    }
    p := &Photo{Name: name} // pretend this is a slow disk read
    cache[name] = weak.Make(p)
    return p
}

func main() {
    onScreen := load("dosa") // the app still shows this one
    load("idli")             // these two are no longer used by anyone
    load("vada")
    runtime.GC()
    for _, n := range []string{"dosa", "idli", "vada"} {
        fmt.Printf("%-5s still cached: %v\n", n, cache[n].Value() != nil)
    }
    fmt.Println("showing:", onScreen.Name)
}

Real output:

dosa  still cached: true
idli  still cached: false
vada  still cached: false
showing: dosa

(Note: the map keys stay; a real cache would also delete entries whose Value() is nil, for example with runtime.AddCleanup.)

Heap size vs live heap

  • Live heap: what marking found reachable (the third number in 12->13->5 MB).
  • Heap size: live heap + garbage not yet swept + the room GOGC lets it grow. A large heap with a small live heap is normal. A leak shows up as a live heap that keeps growing.

What's new: Green Tea (Go 1.26)

Go 1.26 made the Green Tea collector the default. It improves marking of small objects through better locality (working on memory that sits close together) and CPU scalability; the release notes expect "a 10–40% reduction in garbage collection overhead" for programs that use the GC heavily. Opt out at build time with GOEXPERIMENT=nogreenteagc. The compiler on the channel runs Go 1.24.7, so the traces above come from the classic collector; every idea in these notes applies to both.

Mini project: the GC lab

  1. A program that keeps 10 MB live and makes 500 MB of garbage.
  2. Print NumGC, HeapAlloc, TotalAlloc.
  3. A table for GOGC 25, 100, 400, off, and GOGC=off + GOMEMLIMIT=32MiB.
  4. Run one with GODEBUG=gctrace=1 and find the live heap.
  5. A weak cache that frees photos nobody shows.
Solution
// $ go build -o app .
// $ GOGC=25 ./app
// $ GOGC=100 ./app
// $ GOGC=400 ./app
// $ GOGC=off ./app
// $ GOGC=off GOMEMLIMIT=32MiB ./app
// ---- main.go ----
package main

import (
    "fmt"
    "os"
    "runtime"
)

var live [][]byte // 10 MB that stays reachable

func main() {
    for i := 0; i < 100; i++ {
        live = append(live, make([]byte, 100_000))
    }
    for i := 0; i < 5000; i++ { // 5000 x 100 KB = 500 MB of garbage
        b := make([]byte, 100_000)
        b[0] = byte(i)
    }
    var m runtime.MemStats
    runtime.ReadMemStats(&m)
    fmt.Printf("GOGC=%-4s GOMEMLIMIT=%-6s NumGC=%3d HeapAlloc=%3d MB TotalAlloc=%d MB\n",
        os.Getenv("GOGC"), os.Getenv("GOMEMLIMIT"), m.NumGC, m.HeapAlloc>>20, m.TotalAlloc>>20)
}

Real output (one run):

GOGC=25   GOMEMLIMIT=       NumGC=101 HeapAlloc= 11 MB TotalAlloc=518 MB
GOGC=100  GOMEMLIMIT=       NumGC= 22 HeapAlloc= 21 MB TotalAlloc=518 MB
GOGC=400  GOMEMLIMIT=       NumGC=  3 HeapAlloc=395 MB TotalAlloc=518 MB
GOGC=off  GOMEMLIMIT=       NumGC=  0 HeapAlloc=518 MB TotalAlloc=518 MB
GOGC=off  GOMEMLIMIT=32MiB  NumGC= 23 HeapAlloc= 23 MB TotalAlloc=518 MB

The GOGC=400 row varies a lot between runs (another run: NumGC= 7 HeapAlloc= 96 MB): with a far-away goal, a busy two-CPU machine can allocate faster than the concurrent GC finishes a cycle. For step 4, add // $ GODEBUG=gctrace=1 ./app and read the third number of a->b->c MB: it stays near 10.

The weak cache:

package main

import (
    "fmt"
    "runtime"
    "weak"
)

type Photo struct {
    Name   string
    Pixels [1 << 20]byte
}

type Cache struct{ m map[string]weak.Pointer[Photo] }

func (c *Cache) Get(name string) (*Photo, bool) {
    if p := c.m[name].Value(); p != nil {
        return p, true // hit
    }
    p := &Photo{Name: name}
    c.m[name] = weak.Make(p)
    return p, false // miss: loaded again
}

func main() {
    c := &Cache{m: map[string]weak.Pointer[Photo]{}}
    shown, _ := c.Get("dosa")
    c.Get("idli")
    runtime.GC()
    _, hit1 := c.Get("dosa")
    _, hit2 := c.Get("idli")
    fmt.Println("dosa hit:", hit1, " idli hit:", hit2, " showing:", shown.Name)
}

Real output:

dosa hit: true  idli hit: false  showing: dosa

Common mistakes (and the real messages)

Mistake What you see Why Fix
free(b) undefined: free Go has no free drop references; the GC frees
GOGC=off on a server heap now: 207 MB, then an OOM kill nothing is collected GOMEMLIMIT as a ceiling
finalizers on objects in a cycle the finalizer never runs it could resurrect the object runtime.AddCleanup
closing files in a finalizer the file stays open for a long time GC timing is unknown defer f.Close()
a plain map as a cache the live heap keeps growing strong pointers keep everything weak.Pointer, or a size limit
runtime.GC() on a timer wasted CPU the pacer knows better tune GOGC / GOMEMLIMIT
reading heap size as "used memory" "my program uses 20 MB but only 4 MB is live" heap = live + garbage + growth room look at the live heap

Practice

  1. With 50 MB live and GOGC=100, roughly what heap goal does the pacer aim for? With GOGC=200?
  2. Why can't reference counting alone free a.Partner = b; b.Partner = a?
  3. In 5->6->2 MB, 4 MB goal, which number is the live heap?
  4. What happens with GOGC=off and no GOMEMLIMIT in a long-running server?
  5. Why must arg in runtime.AddCleanup(obj, f, arg) not be obj?
Solutions

1. About 100 MB (50 + 50 × 100/100, plus a little for roots); with 200, about 150 MB.

2. Each table is pointed to by the other, so neither count reaches 0 even when nothing else can reach them.

3. 2 MB, the third number.

4. No cycle ever runs; the heap grows with every allocation until the machine or container runs out of memory.

5. If the cleanup held obj, obj would stay reachable through the cleanup and could never be freed, so the cleanup would never run.

Quick quiz

1. gc 9 @0.4s 3%: ..., 12->13->5 MB, 10 MB goal, 2 P with GOGC=100: what does the 5 mean? (From the video.)

A. 5 MB was freed · B. 5 MB is still reachable · C. the heap is 5 MB · D. the next goal is 5 MB

Answer

B. The live heap after marking. The goal is about double: 10 MB.

2. Which colour is an object that's reachable but not yet scanned?

Answer

Grey.

3. What does the write barrier prevent?

Answer

Freeing a reachable object because the program moved a pointer into an already-scanned (black) object during concurrent marking.

Interview questions

  1. How does Go free memory? A concurrent, tri-colour mark-and-sweep garbage collector: it marks everything reachable from the roots and sweeps the rest. There's no free.
  2. Why not reference counting? It can't free cycles on its own and adds work to every pointer copy.
  3. What are the roots? Globals and every goroutine's stack (plus some runtime data).
  4. Why does Go need a write barrier? Because marking runs concurrently with the program; the barrier shades pointer targets so no reachable object is left white.
  5. Is Go's GC stop-the-world? Mostly concurrent; two short STW phases per cycle (sweep termination and mark termination).
  6. What does GOGC do? Sets how much the heap may grow relative to the live heap before the next cycle (default 100); higher = less GC CPU, more memory.
  7. What does GOMEMLIMIT do? A soft memory limit for the runtime (Go 1.19+); the GC works harder near it; GC CPU is capped at about 50% to avoid thrashing.
  8. How do you see GC activity? GODEBUG=gctrace=1, runtime.ReadMemStats, runtime/metrics, heap profiles.
  9. Finalizer vs cleanup? Finalizers get the object and can resurrect it, so cycles with finalizers leak; cleanups (Go 1.24) get a separate value and are preferred.
  10. What is a weak pointer? A pointer that doesn't keep its object alive; Value() returns nil once collected (package weak, Go 1.24).

Glossary

Term Meaning Example
Heap memory for values that outlive their function or are shared a *Bill that escaped
Garbage heap memory the program can never reach again the 15 MB of old bills
Garbage collector (GC) the runtime part that finds and frees garbage Go's mark-and-sweep GC
free C's function to release heap memory by hand undefined: free in Go
Memory leak memory no longer needed but never released a map cache that only grows
Dangling pointer a pointer to memory that was freed use after free in C
Use after free using memory through a dangling pointer a classic C bug
Double free freeing the same memory twice corrupts the allocator
Allocator the code that hands out memory mallocgc in Go
Reference counting freeing an object when its count of pointers reaches 0 count = 2, then 0
Cycle objects pointing at each other in a ring a.Partner = b; b.Partner = a
Root a place the program reads directly: globals, stacks var live [][]byte
Reachable / live can be found by following pointers from a root the open orders
Mark phase finding every reachable object white → grey → black
Sweep phase freeing every object left unmarked the white ones
Tri-colour marking tracking marking with white, grey, black grey = to-do list
White / grey / black not seen / reachable not scanned / reachable and scanned open orders black
Stop the world (STW) pausing all goroutines two tiny pauses per cycle
Concurrent at the same time as the program runs concurrent mark
Write barrier extra code on pointer writes during marking that shades the target grey keeps C alive
Non-moving GC a GC that never moves objects Go's GC
GODEBUG environment variable with runtime debug settings GODEBUG=gctrace=1
gctrace one line per GC cycle on standard error 3->4->4 MB, 4 MB goal
Heap goal the heap size the pacer aims for this cycle 13 MB goal
Pacer decides when the next GC cycle should run uses the live heap and GOGC
GOGC heap growth percentage before the next GC; default 100 GOGC=50, GOGC=off
GOMEMLIMIT soft memory limit for the runtime (Go 1.19+) GOMEMLIMIT=16MiB
Soft limit a limit the runtime tries to respect but may exceed live data larger than the limit
Thrashing GC running constantly so the program can't progress prevented by the ~50% CPU cap
OOM (out of memory) the system kills a program over its memory limit containers
Mebibyte (MiB) 1024 × 1024 bytes 16MiB
runtime.ReadMemStats fills a MemStats with memory numbers m.NumGC
NumGC, HeapAlloc, TotalAlloc, HeapSys GC cycles / heap bytes in use / bytes ever allocated / heap memory from the OS GC cycles: 45
runtime.GC runs a GC cycle now and waits used in demos
debug.SetGCPercent, debug.SetMemoryLimit GOGC and GOMEMLIMIT from code SetGCPercent(200)
Finalizer function run after an object becomes unreachable; gets the object runtime.SetFinalizer
Resurrect make an unreachable object reachable again a finalizer storing t in a global
Cleanup function run after an object is unreachable; gets a separate value runtime.AddCleanup(c, f, c.No)
Strong pointer a normal pointer that keeps its object alive onScreen
Weak pointer a pointer that doesn't keep its object alive weak.Make(p)
weak.Pointer[T].Value the pointer, or nil once collected cache[n].Value()
Live heap vs heap size reachable bytes vs reachable + garbage + growth room 12->13->5 MB
Locality working on memory that sits close together Green Tea's design
Green Tea the GC design that is the default since Go 1.26 GOEXPERIMENT=nogreenteagc to opt out

Summary

  • Freeing by hand causes leaks, dangling pointers and double frees; Go has no free.
  • Reference counting can't free cycles; Go traces from the roots: mark (white → grey → black), then sweep the white.
  • Marking is concurrent, protected by a write barrier, with two tiny stop-the-world pauses.
  • GODEBUG=gctrace=1 shows each cycle: start->end->live MB and the goal.
  • GOGC (default 100) trades CPU for memory; GOMEMLIMIT is a soft ceiling (Go 1.19+).
  • runtime.ReadMemStats, runtime.GC, debug.SetGCPercent, debug.SetMemoryLimit from code.
  • Prefer runtime.AddCleanup to finalizers; use weak.Pointer for caches.
  • Go 1.26: Green Tea GC by default.

Next episode: profiling with pprof: CPU and heap profiles, goroutine, block and mutex profiles, go tool pprof top and list, flame graphs, profile-guided optimisation.