I have a function that generates a random int64
and returns it as an interface{}
like this:
func Val1(rnd rand.Source) interface{} {
return rnd.Int63()
}
now consider this function, which does the same thing but returns a int64
func Val2(rnd rand.Source) int64 {
return rnd.Int63()
}
I benchmarked the two functions with this (go test -bench=. -benchmem
) :
func BenchmarkVal1(b *testing.B) {
var rnd = rand.NewSource(time.Now().UnixNano())
for n := 0; n < b.N; n++ {
Val1(rnd)
}
}
func BenchmarkVal2(b *testing.B) {
var rnd = rand.NewSource(time.Now().UnixNano())
for n := 0; n < b.N; n++ {
Val2(rnd)
}
}
and got folowing results:
BenchmarkVal1-4 50000000 32.4 ns/op 8 B/op 1 allocs/op
BenchmarkVal2-4 200000000 7.47 ns/op 0 B/op 0 allocs/op
Where does the extra allocation in Val1()
come from ? Can it be avoided when returning an interface{}
?