Created
February 12, 2020 23:30
-
-
Save bradford-hamilton/83fa23999623432a60a1d149cf89e959 to your computer and use it in GitHub Desktop.
This file contains hidden or 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 | |
import ( | |
"fmt" | |
"reflect" | |
"strconv" | |
"testing" | |
) | |
// benchmarkisPointerTypeAssertion 31.2 ns/op | |
// MemAllocs: 39508114 | |
// MemBytes: 315791384 | |
// benchmarkisPointerReflect 55.5 ns/op | |
// MemAllocs: 43794600 | |
// MemBytes: 525258872 | |
func main() { | |
res := testing.Benchmark(benchmarkisPointerTypeAssertion) | |
fmt.Printf("%s\n%#[1]v\n", res) | |
fmt.Printf("MemAllocs: %d\n", res.MemAllocs) | |
fmt.Printf("MemBytes: %d\n", res.MemBytes) | |
res = testing.Benchmark(benchmarkisPointerReflect) | |
fmt.Printf("%s\n%#[1]v\n", res) | |
fmt.Printf("MemAllocs: %d\n", res.MemAllocs) | |
fmt.Printf("MemBytes: %d\n", res.MemBytes) | |
} | |
func benchmarkisPointerTypeAssertion(b *testing.B) { | |
for i := 0; i < b.N; i++ { | |
_ = isPointerTypeAssertion(strconv.Itoa(i)) | |
} | |
} | |
func benchmarkisPointerReflect(b *testing.B) { | |
for i := 0; i < b.N; i++ { | |
_ = isPointerReflect(strconv.Itoa(i)) | |
} | |
} | |
func isPointerTypeAssertion(arg interface{}) bool { | |
switch arg.(type) { | |
case *string: | |
return true | |
default: | |
return false | |
} | |
} | |
func isPointerReflect(arg interface{}) bool { | |
return reflect.ValueOf(arg).Kind() == reflect.Ptr | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment