LoginSignup
0
0

More than 5 years have passed since last update.

Go言語 キャストvs代入

Last updated at Posted at 2019-02-19

はじめに

structを別structにキャストするときどうすれば早いのかベンチマークとりました。

何と何を?

キャストした場合と

n := Foo{M: msg}
b := Bar(n)

メンバーを代入した場合です。

n := Foo{M: msg}
b := Bar{
    M: n.M,
}

結論

普通にキャストした方が早いです。

検証

hoge.go
package hoge

type Foo struct {
    M string
}

type Bar struct {
    M string
}

const msg = "hgoe"

func Cast() Bar {
    n := Foo{M: msg}
    return Bar(n)
}

func Substitute() Bar {
    n := Foo{M: msg}
    b := Bar{
        M: n.M,
    }
    return b
}
hoge_test.go
package hoge

import "testing"

func BenchmarkCast(b *testing.B) {
    b.Run("cast", func(b *testing.B) {
        b.ResetTimer()
        for i := 0; i < b.N; i++ {
            Cast()
        }
    })
    b.Run("sub", func(b *testing.B) {
        b.ResetTimer()
        for i := 0; i < b.N; i++ {
            Substitute()
        }
    })
}

キャストの方が2倍くらい早いです。

結果
goos: darwin
goarch: amd64
pkg: test/cast
BenchmarkCast/cast-8            2000000000           0.34 ns/op
BenchmarkCast/sub-8             2000000000           0.61 ns/op
PASS

以上です。

0
0
4

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
0