Why does calling a function in a struct with a slice cause heap allocation?

Viewed 49
package main

import (
    "testing"
)

type Wrap struct {
    Stack []func(next Wrap)
    One   func(next Wrap)
}


func BenchmarkAllocates(b *testing.B) {
    for i := 0; i < b.N; i++ {
        x := Wrap{
            Stack: []func(w Wrap){
                func(w Wrap) {
                },
            }, // why does this allocate?
        }
        x.Stack[0](x)
    }
}

func BenchmarkNoAllocate(b *testing.B) {
    for i := 0; i < b.N; i++ {
        x := Wrap{
            One: func(w Wrap) {
            },
        }
        x.One(x)
    }
}

go playground

go test -benchmem

Why does BenchmarkNoAllocate cause memory to be allocated in the heap? Is there a way to avoid that but still pass a slice?

As far as I know both slice and func are pointer types, so I'd assume either both or neither to allocate.

0 Answers
Related