Last active
January 18, 2024 15:53
-
-
Save nfisher/a9aa2d34fedb338667bf to your computer and use it in GitHub Desktop.
Golang - Benchmark of new vs reflect.New.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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" | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
$ 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