Skip to content

Instantly share code, notes, and snippets.

@jiacai2050
Created March 15, 2020 05:23
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jiacai2050/7354648a5cae59762640cd20e5022db4 to your computer and use it in GitHub Desktop.
Save jiacai2050/7354648a5cae59762640cd20e5022db4 to your computer and use it in GitHub Desktop.
go value vs pointer benchmark
package main
import "testing"
var blackholeStr = ""
var blackholeValue student
var blackholePointer *student
func BenchmarkPointerVSStruct(b *testing.B) {
b.Run("return pointer", func(b *testing.B) {
b.ReportAllocs()
b.ResetTimer()
for i := 0; i < b.N; i++ {
blackholePointer = returnByPointer()
}
})
b.Run("return value", func(b *testing.B) {
b.ReportAllocs()
b.ResetTimer()
for i := 0; i < b.N; i++ {
blackholeValue = returnByValue()
}
})
b.Run("value receiver", func(b *testing.B) {
b.ReportAllocs()
b.ResetTimer()
for i := 0; i < b.N; i++ {
r := student{
name: randStr,
}
blackholeStr = r.getNameByValue()
}
})
b.Run("pointer receiver", func(b *testing.B) {
b.ReportAllocs()
b.ResetTimer()
for i := 0; i < b.N; i++ {
r := &student{
name: randStr,
}
blackholeStr = r.getNameByPointer()
}
})
}
go test -run ^NOTHING -bench Struct bench_test.go snippet.go
goos: darwin
goarch: amd64
BenchmarkPointerVSStruct/return_pointer-8 34476903 32.4 ns/op 16 B/op 1 allocs/op
BenchmarkPointerVSStruct/return__value-8 530538498 2.27 ns/op 0 B/op 0 allocs/op
BenchmarkPointerVSStruct/value_receiver-8 415309486 2.86 ns/op 0 B/op 0 allocs/op
BenchmarkPointerVSStruct/pointer_receiver-8 348904872 3.23 ns/op 0 B/op 0 allocs/op
PASS
ok command-line-arguments 5.699s
// -*- mode:go;mode:go-playground -*-
// snippet of code @ 2020-03-15 11:33:13
// === Go Playground ===
// Execute the snippet with Ctl-Return
// Provide custom arguments to compile with Alt-Return
// Remove the snippet completely with its dir and all files M-x `go-playground-rm`
package main
import (
"fmt"
)
type student struct {
name string
}
//go:noinline
func (s student) getNameByValue() string {
return s.name
}
//go:noinline
func (s *student) getNameByPointer() string {
return s.name
}
const randStr = "a very long string,a very long string,a very long string,a very long string"
//go:noinline
func returnByValue() student {
return student{randStr}
}
//go:noinline
func returnByPointer() *student {
return &student{randStr}
}
func main() {
foo := student{name: "foo"}
bar := foo
bar.name = "bar"
fmt.Println(foo.name)
bar2 := &foo
bar2.name = "bar"
fmt.Println(foo.name)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment