A simple Go project to experiment slice memory allocation strategies using pprof.
Run the unoptimized dynamic append version:
go run main.go -type=badRun the optimized pre-allocation version:
go run main.go -type=goodVisualize the memory profile in your browser:
go tool pprof -http=:8080 mem.prof~2MB: Uses a fixed-size slice and reuses memory.
- A Go string header is 16 bytes (pointer + length).
-
$16 \text{ bytes} \times 100,000 \text{ elements} \approx 1.6 \text{ MB}$ . - Since the size is constant, memory usage never exceeds this baseline.
~27.4GB: Uses append, causing the slice to grow indefinitely for 5 seconds.
-
$16 \text{ bytes} \times 1.7\text{B elements} \approx 27.2 \text{ GB}$ . - With 100,000 appends per loop running ~17,000 times, the slice reaches 1.7 billion elements.
- The massive consumption comes from the ever-expanding backing array.