Skip to content

Instantly share code, notes, and snippets.

@nfisher
Last active January 18, 2024 15:53
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save nfisher/a9aa2d34fedb338667bf to your computer and use it in GitHub Desktop.
Save nfisher/a9aa2d34fedb338667bf to your computer and use it in GitHub Desktop.
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