Skip to content

Instantly share code, notes, and snippets.

@nfisher
Last active January 27, 2022 19:02
  • Star 1 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
Star You must be signed in to star a gist
Embed
What would you like to do?
Golang - Benchmark of new vs reflect.New.
package main_test
import (
"reflect"
"testing"
)
type fluff struct {
Name string
}
func Benchmark_reflection(b *testing.B) {
var arg *fluff
argv := reflect.TypeOf(fluff{})
for i := 0; i < b.N; i++ {
argn := reflect.New(argv)
arg, _ = argn.Interface().(*fluff)
arg.Name = "Bob"
}
}
func Benchmark_new(b *testing.B) {
var arg *fluff // think this is necessary for escape analysis
for i := 0; i < b.N; i++ {
arg = new(fluff)
arg.Name = "Bob"
}
}
$ go test -bench . reflect_test.go # uBenchmarks silliness in a box
testing: warning: no tests to run
PASS
Benchmark_reflection 20000000 110 ns/op
Benchmark_new 30000000 57.7 ns/op
ok command-line-arguments 4.125s
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment