Skip to content

Instantly share code, notes, and snippets.

@bcicen
Last active March 15, 2019 04:47
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save bcicen/b532c2932ca341febab80e669768e21f to your computer and use it in GitHub Desktop.
Save bcicen/b532c2932ca341febab80e669768e21f to your computer and use it in GitHub Desktop.
package main
import (
"testing"
)
var (
lastString string
lastNumber int
lastBool bool
lastArr []interface{}
lastObj map[string]interface{}
items = []interface{}{
nil,
"Dj",
"mU",
"et",
1921,
84,
1964,
true,
false,
[]interface{}{"YJ", "OP", "ST", "fS"},
map[string]interface{}{
"fF": "ib",
"Pp": "iD",
"eD": "ad",
"Iu": "ig",
},
}
itemTypes = []ValueType{
Null,
String,
String,
String,
Number,
Number,
Number,
Boolean,
Boolean,
Array,
Object,
}
buf1 []Struct1
buf2 []Struct2
)
type ValueType int
const (
Unknown ValueType = iota
Null
String
Number
Boolean
Array
Object
)
type Struct1 struct {
value interface{}
}
type Struct2 struct {
value interface{}
valueType ValueType
}
func BenchmarkTypeSwitchPopulate(b *testing.B) {
for i := 0; i < b.N; i++ {
var pos int
buf1 = make([]Struct1, 1000)
for n := 0; n < len(buf1); n++ {
buf1[n] = Struct1{items[pos]}
pos++
if pos >= len(items) {
pos = 0
}
}
}
}
func BenchmarkTypeFieldPopulate(b *testing.B) {
for i := 0; i < b.N; i++ {
var pos int
buf2 = make([]Struct2, 1000)
for n := 0; n < len(buf2); n++ {
buf2[n] = Struct2{items[pos], itemTypes[pos]}
pos++
if pos >= len(items) {
pos = 0
}
}
}
}
func BenchmarkTypeSwitch(b *testing.B) {
for i := 0; i < b.N; i++ {
for n := 0; n < len(buf1); n++ {
readTypeSwitch(b, buf1[n].value)
}
}
}
func readTypeSwitch(b *testing.B, val interface{}) {
switch val := val.(type) {
case string:
lastString = val
case int:
lastNumber = val
case bool:
lastBool = val
case []interface{}:
lastArr = val
case map[string]interface{}:
lastObj = val
case nil:
default:
b.Fatalf("unhandled type (%v) (%T)", val, val)
}
}
func BenchmarkTypeField(b *testing.B) {
for i := 0; i < b.N; i++ {
for n := 0; n < len(buf2); n++ {
readTypeField(b, buf2[n].valueType, buf2[n].value)
}
}
}
func readTypeField(b *testing.B, vt ValueType, val interface{}) {
switch vt {
case String:
lastString = val.(string)
case Number:
lastNumber = val.(int)
case Boolean:
lastBool = val.(bool)
case Array:
lastArr = val.([]interface{})
case Object:
lastObj = val.(map[string]interface{})
case Null:
default:
b.Fatalf("unhandled type (%v) (%T)", val, val)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment