# Go Memory Quick Reference

## pprof Commands

| Command | Shows |
|---------|-------|
| `go tool pprof -top -alloc_space prof` | Total bytes allocated (all time) |
| `go tool pprof -top -alloc_objects prof` | Total objects allocated (GC pressure) |
| `go tool pprof -top -inuse_space prof` | Currently live bytes (not freed) |
| `go tool pprof -top -inuse_objects prof` | Currently live objects |
| `go tool pprof -list=FuncName prof` | Source-annotated allocations |
| `go tool pprof -svg prof > out.svg` | Allocation graph |

## Escape Analysis Quick Check

```bash
# One-liner: count escapes per file
go build -gcflags='-m' ./... 2>&1 | grep 'escapes to heap' | sed 's/:.*//g' | sort | uniq -c | sort -rn | head -10
```

## Common Escape Triggers

| Trigger | Escape? | Fix |
|---------|---------|-----|
| `return &local` | YES | Return by value |
| `interface{} = local` | YES (boxing) | Use concrete type or generics |
| `ch <- &local` | YES | Send by value if small |
| `go func() { use(local) }` | YES (closure capture) | Pass as parameter |
| `append(slice, &local)` | YES | Append value, not pointer |
| Large struct (>64KB) | YES (too big for stack) | Consider pointer + pool |

## GC Tuning

| Env var | Default | Effect |
|---------|---------|--------|
| `GOGC=100` | 100 | GC when heap doubles. Higher = less GC, more memory |
| `GOGC=off` | - | Disable GC (batch jobs only) |
| `GOMEMLIMIT=1GiB` | none | Soft memory limit, GC adapts (Go 1.19+) |
| `GOGC=off` + `GOMEMLIMIT` | - | Minimize GC for batch jobs with bounded memory |
| `GODEBUG=gctrace=1` | off | Print GC activity to stderr |

## Struct Alignment Linter

```bash
go install golang.org/x/tools/go/analysis/passes/fieldalignment/cmd/fieldalignment@latest
fieldalignment ./...
```

## Benchmark Reference Numbers

| Pattern | Before | After | Improvement |
|---------|--------|-------|-------------|
| Pre-allocate slices | Dynamic grow | `make([]T, 0, n)` | **4× faster**, fewer allocs |
| sync.Pool reuse | 864 ns/op | 42 ns/op | **20× throughput** |
| Struct field alignment (10M) | 240 MB | 160 MB | **80 MB saved** (33%) |
| False sharing prevention | 996 µs/op | 958 µs/op | ~3.8% (concurrent) |
| Buffered I/O writes | 23.6 ms/op | 380 µs/op | **62× faster** |
| Batched file writes | 12.7 ms/op | 994 µs/op | **12× faster** |
| Batched crypto (SHA256) | 1.23 ms/op | 675 µs/op | **~2× faster** |
| mmap vs os.File.Read | baseline | mmap | **~2× faster** |

## benchstat Reading Guide

```
name         old allocs/op  new allocs/op  delta
Process-8    1.20k ± 1%     0.45k ± 0%    -62.50%  (p=0.000 n=10+10)
```
- `old`/`new`: Before/after values
- `±`: Variation across runs (lower = more stable)
- `delta`: Percentage change (negative = improvement for allocs)
- `p`: Statistical significance (p < 0.05 = significant)
- `n`: Number of samples used
