Skip to content

Instantly share code, notes, and snippets.

@jufuku
Last active January 8, 2019 04:19
Show Gist options
  • Save jufuku/14ec0d6a7c27d910d435a35f68c6fa5e to your computer and use it in GitHub Desktop.
Save jufuku/14ec0d6a7c27d910d435a35f68c6fa5e to your computer and use it in GitHub Desktop.
package main
import (
"reflect"
"testing"
)
type Hoge struct {
ID int64
Name string
}
type Hoge2 struct {
ID2 int64
Name2 string
}
var (
list = []Hoge{{1, "Mark"}, {2, "John"}, {3, "Bob"}, {4, "Alex"}}
list2 = []Hoge2{{1, "Mark"}, {2, "John"}, {3, "Bob"}, {4, "Alex"}}
)
// ①for文で直接抜き出すパターン
func Benchmark_NormalLoop(b *testing.B) {
for i := 0; i < b.N; i++ {
ids := make([]int64, len(list))
for i, v := range list {
ids[i] = v.ID
}
ids2 := make([]int64, len(list2))
for i, v := range list2 {
ids2[i] = v.ID2
}
}
}
// ②reflectパッケージで処理するパターン
func Benchmark_ReflectLoop(b *testing.B) {
for i := 0; i < b.N; i++ {
GetInt64SlicesBySpecifiedField(&list, `ID`)
GetInt64SlicesBySpecifiedField(&list2, `ID2`)
}
}
func GetInt64SlicesBySpecifiedField(p interface{}, fieldName string) []int64 {
v := reflect.ValueOf(p).Elem()
len := v.Len()
slices := make([]int64, len)
switch v.Kind() {
case reflect.Slice:
for i := 0; i < len; i++ {
slices[i] = v.Index(i).FieldByName(fieldName).Int()
}
}
return slices
}
// ③IFでの実装パターン
func Benchmark_IFLoop(b *testing.B) {
for i := 0; i < b.N; i++ {
getIDs(list3)
getIDs(list4)
}
}
type HogesI interface {
GetIDs() []int64
}
func getIDs(list HogesI) []int64 {
return list.GetIDs()
}
type Hoges []Hoge
func (h *Hoges) GetIDs() []int64 {
ids := make([]int64, len(*h))
for i, v := range *h {
ids[i] = v.ID
}
return ids
}
type Hoges2 []Hoge2
func (h *Hoges2) GetIDs() []int64 {
ids := make([]int64, len(*h))
for i, v := range *h {
ids[i] = v.ID2
}
return ids
}
var (
list3 = &Hoges{
Hoge{1, "Mark"},
Hoge{2, "John"},
Hoge{3, "Bob"},
Hoge{4, "Alex"},
}
list4 = &Hoges2{
Hoge2{1, "Mark"},
Hoge2{2, "John"},
Hoge2{3, "Bob"},
Hoge2{4, "Alex"},
}
)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment