はじめに
- Go 言語で interface から他の型への変換をする型アサーションの際に interface 型をその場で指定することができるということを最近知った。
out, ok := in.(interface {
SomeFunc()
})
- 型制約をあえてゆるくしたいときに使える場合もあるかもしれないので、よくあるような事前に型を定義しておく場合と比べて遅くなったりしないのか計測してみる。
テストコード
package main
import "testing"
type struct1 struct {
}
func (s *struct1) Read() {
}
type interface1 interface {
Read()
}
func func1(in interface{}) bool {
_, ok := in.(interface1)
return ok
}
func func2(in interface{}) bool {
_, ok := in.(interface {
Read()
})
return ok
}
func TestFunc1(t *testing.T) {
s := &struct1{}
if !func1(s) {
t.Error("failed")
}
}
func TestFunc2(t *testing.T) {
s := &struct1{}
if !func2(s) {
t.Error("failed")
}
}
func BenchmarkFunc1(b *testing.B) {
s := &struct1{}
for i := 0; i < b.N; i++ {
func1(s)
}
}
func BenchmarkFunc2(b *testing.B) {
s := &struct1{}
for i := 0; i < b.N; i++ {
func2(s)
}
}
テスト結果
- 何回か実行してみて有意な差はなさそう
BenchmarkFunc1-4 100000000 13.2 ns/op
BenchmarkFunc2-4 100000000 13.7 ns/op
BenchmarkFunc1-4 100000000 12.4 ns/op
BenchmarkFunc2-4 100000000 12.2 ns/op
BenchmarkFunc1-4 100000000 12.4 ns/op
BenchmarkFunc2-4 100000000 12.5 ns/op
BenchmarkFunc1-4 100000000 12.2 ns/op
BenchmarkFunc2-4 100000000 12.7 ns/op