golang type assertion and unsafe.Pointer 性能对比
最近项目中有这样一个需求背景:有一个存储实体用来做各种指标的counter。这个counter的实现需要能够在以后被别的实现替换。结构自然是这样:
type XXXObj struct {
startTime uint64
counter interface{
}//暂时用interface{}表示,表示该对象类似于泛型的存在
}
为了避免对象拷贝,所以其实这里存储的一定会是一个指针。所以这里还有一个可选方案:unsafe.Pointer.
最初的设计,这一块更像泛型的一种思想,所以很自然的使用了interface{}。
但是上层拿到这个 interface{} 之后肯定要做类型断言,转成实际的counter对象指针,然后执行实际的统计操作。这一块是一个非常高频的调用。所以performance是非常重要的点。
所以想测试一下:直接调用、类型断言,unsafe.Pointer转换三种方式的性能对比。下面是一个test 的benchmark。这里申明一下这里仅仅针对泛型对象是指针的场景:
package assertion
import (
"testing"
"unsafe"
)
type Student struct {
Name string
Age int
Class string
Score int
}
func DirectInvoke(s *Student) {
s.N