Skip to content

Instantly share code, notes, and snippets.

@bradford-hamilton
Created February 12, 2020 23:30
Show Gist options
  • Save bradford-hamilton/83fa23999623432a60a1d149cf89e959 to your computer and use it in GitHub Desktop.
Save bradford-hamilton/83fa23999623432a60a1d149cf89e959 to your computer and use it in GitHub Desktop.
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