```go
type Prop[T any] struct {
val T
}
type PropI[T Ivalue] struct {
val T
}
func (this *PropI[T]) GetDataS() string {
return this.val.GetData()
}
type PropV struct {
val any
}
type PropIV struct {
val Ivalue
}
type PropValue struct {
val *value
}
type value struct {
data string
}
func (this *value) GetData() string {
return this.data
}
type Ivalue interface {
GetData() string
}
func BenchmarkPropValue(b *testing.B) {
for i := 0; i < b.N; i++ {
a := new(PropValue)
a.val = &value{"data"}
a.val.GetData()
}
}
func BenchmarkPropIvalue(b *testing.B) {
for i := 0; i < b.N; i++ {
a := new(PropIV)
a.val = &value{"data"}
var b = a.val
_ = b
b.GetData()
// fmt.Println(b)
}
}
func BenchmarkPropVByInterface(b *testing.B) {
for i := 0; i < b.N; i++ {
a := new(PropV)
a.val = &value{"data"}
var b = a.val.(Ivalue)
_ = b
b.GetData()
// fmt.Println(b)
}
}
func BenchmarkPropTByInterface(b *testing.B) {
for i := 0; i < b.N; i++ {
a := new(Prop[Ivalue])
a.val = &value{"data"}
var b Ivalue = a.val
_ = b
b.GetData()
// fmt.Println(b)
}
}
func BenchmarkPropTByIValue(b *testing.B) {
for i := 0; i < b.N; i++ {
a := new(PropI[*value])
a.val = &value{"data"}
a.val.GetData()
}
}
func BenchmarkPropTByIValueFunc(b *testing.B) {
for i := 0; i < b.N; i++ {
a := new(PropI[*value])
a.val = &value{"data"}
a.GetDataS()
}
}
func BenchmarkPropTByValue(b *testing.B) {
for i := 0; i < b.N; i++ {
a := new(Prop[*value])
a.val = &value{"data"}
var b *value = a.val
_ = b
b.GetData()
}
}
func BenchmarkPropTByint32(b *testing.B) {
for i := 0; i < b.N; i++ {
a := new(Prop[int32])
a.val = 11
var b int32 = a.val
_ = b
}
}
func BenchmarkPropVByint32(b *testing.B) {
for i := 0; i < b.N; i++ {
a := new(PropV)
a.val = int32(11)
var b int32 = a.val.(int32)
_ = b
}
}
```
测试结果:
```
BenchmarkPropValue-12 51983382 22.12 ns/op 16 B/op 1 allocs/op
BenchmarkPropIvalue-12 52064125 22.96 ns/op 16 B/op 1 allocs/op
BenchmarkPropVByInterface-12 35158447 34.03 ns/op 16 B/op 1 allocs/op
BenchmarkPropTByInterface-12 41340108 24.72 ns/op 16 B/op 1 allocs/op
BenchmarkPropTByIValue-12 53881003 22.29 ns/op 16 B/op 1 allocs/op
BenchmarkPropTByIValueFunc-12 53747065 23.84 ns/op 16 B/op 1 allocs/op
BenchmarkPropTByValue-12 54542726 22.27 ns/op 16 B/op 1 allocs/op
BenchmarkPropTByint32-12 1000000000 0.2349 ns/op 0 B/op 0 allocs/op
BenchmarkPropVByint32-12 1000000000 0.2334 ns/op 0 B/op 0 allocs/op
```
结论:
golang的泛型的性能与写实际类型的性能是一样的。这样比我们有时候把成员写成interface性能要高。
有疑问加站长微信联系(非本文作者)