Skip to content

Instantly share code, notes, and snippets.

@robherley
Created November 12, 2025 14:50
Show Gist options
  • Select an option

  • Save robherley/13e2b401ce4dd26afb9fabf39e99b2ea to your computer and use it in GitHub Desktop.

Select an option

Save robherley/13e2b401ce4dd26afb9fabf39e99b2ea to your computer and use it in GitHub Desktop.
Slice Allocs
slice[cap=0]: allocs: 0, 0 bytes
  adding 10000 elements cost: allocs: 20, 357648 bytes
slice[cap=5000]: allocs: 1, 40960 bytes
  adding 10000 elements cost: allocs: 4, 229392 bytes
slice[cap=10000]: allocs: 1, 81920 bytes
  adding 10000 elements cost: allocs: 0, 0 bytes

Adding 10,000 elements to a slice with an initial capacity of 0 will become 357648 bytes. Of which ~88% (~19 other slice allocations) would be unused slices that would need to be GC'd.

package main
import (
"fmt"
"runtime"
)
const N = 10_000
func diff(fn func()) (int64, uint64) {
runtime.GC()
var before, after runtime.MemStats
runtime.ReadMemStats(&before)
fn()
runtime.ReadMemStats(&after)
return int64(after.Mallocs - before.Mallocs), after.TotalAlloc - before.TotalAlloc
}
func appendN(s []int, n int) []int {
for i := range n {
s = append(s, i)
}
return s
}
func main() {
caps := []int{0, N / 2, N}
for _, c := range caps {
var slice []int
a, m := diff(func() {
slice = make([]int, 0, c)
})
fmt.Printf("slice[cap=%d]: allocs: %d, %d bytes\n", cap(slice), a, m)
a, m = diff(func() {
_ = appendN(slice, N)
})
fmt.Printf(" adding %d elements cost: allocs: %d, %d bytes\n", N, a, m)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment