Skip to content

Instantly share code, notes, and snippets.

@goccy
Created January 25, 2019 13:36
Show Gist options
  • Save goccy/f53c3d46f8f0639fcb11fd4de57c7681 to your computer and use it in GitHub Desktop.
Save goccy/f53c3d46f8f0639fcb11fd4de57c7681 to your computer and use it in GitHub Desktop.
```go
package main
import (
"testing"
)
type Value struct {
uintValue uint
uint64Value uint64
LT func(*Value) bool
}
func NewUintValue(v uint) *Value {
return &Value{
uintValue: v,
LT: func(value *Value) bool {
return v < value.uintValue
},
}
}
type InterfaceValue interface {
LT(InterfaceValue) bool
}
type UintValue uint
func (v UintValue) LT(value InterfaceValue) bool {
return v < value.(UintValue)
}
func compareStruct(src *Value, dst *Value) bool {
return src.LT(dst)
}
func compareInterface(src InterfaceValue, dst InterfaceValue) bool {
return src.LT(dst)
}
func Benchmark_Struct(b *testing.B) {
b.ResetTimer()
src := NewUintValue(1)
dst := NewUintValue(2)
for n := 0; n < b.N; n += 1 {
for i := 1; i <= 100; i += 1 {
compareStruct(src, dst)
}
}
}
func Benchmark_Interface(b *testing.B) {
b.ResetTimer()
src := UintValue(1)
dst := UintValue(2)
for n := 0; n < b.N; n += 1 {
for i := 1; i <= 100; i += 1 {
compareInterface(src, dst)
}
}
}
```
```
$ go test -bench . -benchmem
goos: darwin
goarch: amd64
Benchmark_Struct-8 5000000 378 ns/op 0 B/op 0 allocs/op
Benchmark_Interface-8 500000 3506 ns/op 1600 B/op 200 allocs/op
PASS
```
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment