why the result of calling by pointer and interface are different? calling by interface takes heap memory and is so slow., while calling by pointer is extremely fast without engaging by Heap.
The following codes benchmarks shows difference clearly. Naturally I expect the result be same. but is different completely.
#go version
go version go1.22.4 linux/amd64
I faced with unexpected memory allocation and finally discovered that using of interface causes unexpected extra heap allocation. I wrote two benchmarks and compare them with each other. I expect the same result. I don’t expect extra memory allocation by using of interfaces.
package main
import "testing"
type S struct{ _ [128]byte }
type Interface interface{ Play(*S) }
type Child struct{}
func (Child) Play(s *S) {}
type IParent struct{ Child Interface } //interface
type Parent struct{ Child *Child } //pointer
func (parent IParent) Work() (s S) { parent.Child.Play(&s); return }
func (parent Parent) Work() (s S) { parent.Child.Play(&s); return }
func BenchmarkInterface(b *testing.B){for range b.N{ IParent{&Child{}}.Work()}}
func BenchmarkPointer(b *testing.B){for range b.N{ Parent{&Child{}}.Work()}}
#go test -bench=. -benchmem -cpu 1
BenchmarkInterface 18390373 64.38 ns/op 128 B/op 1 allocs/op
BenchmarkPointer 1000000000 0.3562 ns/op 0 B/op 0 allocs/op
Bahador Nazarifard is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.