Here I have a benchmark test:
// bench_test.go
package main
import (
"testing"
)
func BenchmarkHello(b *testing.B) {
for i := 0; i < b.N; i++ {
a := 1
a++
}
}
The test result are strange. The metric allocs/op
shows zero. I know variable a
is a int type and doesn't take too much memory, but it's not zero.
> go test -bench=. -benchmem
goos: darwin
goarch: amd64
pkg: a
BenchmarkHello-4 2000000000 0.26 ns/op 0 B/op 0 allocs/op
PASS
ok a 0.553s
This post points that allocs/op
means how many distinct memory allocations occurred per op (single iteration).
But what does memory allocation
mean? does that mean set a value for a variable? Is it kind of
malloc in C` ?
Why is this metric allocs/ops
zero?
From Dave Cheney, one of the Go contributors:
The benchmark tool only reports heap allocations. Stack allocations via escape analysis are less costly, possibly free, so are not reported.
Why is this metric allocs/ops zero?
package main import ( "testing" ) func BenchmarkHello(b *testing.B) { for i := 0; i < b.N; i++ { a := 1 a++ } }
The allocs/ops average only counts heap allocations, not stack allocations.
The allocs/ops average is rounded down to the nearest integer value.
The Go gc compiler is an optimizing compiler. Since
{
a := 1
a++
}
doesn't accomplish anything, it is elided.