What version of Go are you using (go version)?
$ go version
go version go1.18.3 linux/amd64
What operating system and processor architecture are you using (go env)?
go env Output
$ go env
GO111MODULE=""
GOARCH="amd64"
GOBIN=""
GOCACHE="/home/illia/.cache/go-build"
GOENV="/home/illia/.config/go/env"
GOEXE=""
GOEXPERIMENT=""
GOFLAGS=""
GOHOSTARCH="amd64"
GOHOSTOS="linux"
GOINSECURE=""
GOMODCACHE="/home/illia/go/pkg/mod"
GONOPROXY=""
GONOSUMDB=""
GOOS="linux"
GOPATH="/home/illia/go"
GOPRIVATE=""
GOPROXY="https://proxy.golang.org,direct"
GOROOT="/usr/local/go"
GOSUMDB="sum.golang.org"
GOTMPDIR=""
GOTOOLDIR="/usr/local/go/pkg/tool/linux_amd64"
GOVCS=""
GOVERSION="go1.18.3"
GCCGO="gccgo"
GOAMD64="v1"
AR="ar"
CC="gcc"
CXX="g++"
CGO_ENABLED="1"
GOMOD="/dev/null"
GOWORK=""
CGO_CFLAGS="-g -O2"
CGO_CPPFLAGS=""
CGO_CXXFLAGS="-g -O2"
CGO_FFLAGS="-g -O2"
CGO_LDFLAGS="-g -O2"
PKG_CONFIG="pkg-config"
GOGCCFLAGS="-fPIC -m64 -pthread -fmessage-length=0 -fdebug-prefix-map=/tmp/go-build2942373244=/tmp/go-build -gno-record-gcc-switches"
What did you do?
func ToBytes(s string) []byte {
ptr := unsafe.Pointer(&s)
slice := *(*[]byte)(ptr)
return slice[:(*reflect.SliceHeader)(ptr).Len]
}
func BenchmarkToBytes(b *testing.B) {
for i := 0; i < b.N; i++ {
ToBytes("Hello, world!")
}
}
func main() {
alloc := testing.AllocsPerRun(1, func() {
ToBytes("Hello, world!")
})
fmt.Println("Total allocations:", alloc)
}
go run .
go test -bench=BenchmarkToBytes -count=1
What did you expect to see?
Same numbers of the allocations
What did you see instead?
$ go run .
Total allocations: 0
$ go test -bench=BenchmarkToBytes -count=1
goos: linux
goarch: amd64
cpu: Intel(R) Core(TM) i5-2540M CPU @ 2.60GHz
BenchmarkToBytes-4 1000000000 0.6898 ns/op
What version of Go are you using (
go version)?What operating system and processor architecture are you using (
go env)?go envOutputWhat did you do?
What did you expect to see?
Same numbers of the allocations
What did you see instead?
$ go run . Total allocations: 0$ go test -bench=BenchmarkToBytes -count=1 goos: linux goarch: amd64 cpu: Intel(R) Core(TM) i5-2540M CPU @ 2.60GHz BenchmarkToBytes-4 1000000000 0.6898 ns/op