Skip to content

Instantly share code, notes, and snippets.

@lysu
Last active July 3, 2019 04:57
Show Gist options
  • Save lysu/4398f2c46548af99708f09475ab72d03 to your computer and use it in GitHub Desktop.
Save lysu/4398f2c46548af99708f09475ab72d03 to your computer and use it in GitHub Desktop.
package tikvrpc
import (
"github.com/pingcap/kvproto/pkg/kvrpcpb"
"testing"
"unsafe"
)
type S1 struct {
in interface{}
}
func (s *S1) Get() *kvrpcpb.GetResponse {
switch x := s.in.(type) {
case *kvrpcpb.GetResponse:
return x
default:
return nil
}
}
func (s *S1) Set(in interface{}) {
switch x := in.(type) {
case *kvrpcpb.GetResponse:
s.in = x
default:
panic("111")
}
}
type S2 struct {
typ int
in uintptr
}
func (s *S2) Get() *kvrpcpb.GetResponse {
switch s.typ {
case 1:
return (*kvrpcpb.GetResponse)(unsafe.Pointer(s.in))
default:
return nil
}
}
func (s *S2) Set(typ int, in uintptr) {
switch typ {
case 1:
s.typ = typ
s.in = in
default:
panic("121212")
}
}
func BenchmarkInterface(b *testing.B) {
var s1 S1
var (
x kvrpcpb.GetResponse
y kvrpcpb.GetResponse
)
for i := 0; i < b.N; i++ {
s1.Set(&x)
s1.Get()
s1.Set(&y)
s1.Get()
}
}
func BenchmarkUnsafe(b *testing.B) {
var s2 S2
var (
x kvrpcpb.GetResponse
y kvrpcpb.GetResponse
)
for i := 0; i < b.N; i++ {
s2.Set(1, uintptr(unsafe.Pointer(&x)))
s2.Get()
s2.Set(1, uintptr(unsafe.Pointer(&y)))
s2.Get()
}
}
@lysu
Copy link
Author

lysu commented Jul 3, 2019

goos: linux
goarch: amd64
pkg: github.com/pingcap/tidb/store/tikv/tikvrpc
BenchmarkInterface-8 100000000 11.2 ns/op
BenchmarkUnsafe-8 2000000000 0.52 ns/op
PASS

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment