LoginSignup
0
1

More than 5 years have passed since last update.

Go 言語の型アサーションの型指定で interface を定義する場合の速度計測

Posted at

はじめに

  • 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
0
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
1