测试用例
  我们对Golang的结构体变量赋值, 以及单参数函数调用进行反射和native操作的测试
package main
import (
"reflect"
"testing"
)
type data struct {
Hp int
}
const AssignTimes = 100000000
func TestNativeAssign(t *testing.T) {
v := data{Hp: 2}
for i := 0; i < AssignTimes; i++ {
v.Hp = 3
}
}
func TestReflectAssign(t *testing.T) {
v := data{Hp: 2}
vv := reflect.ValueOf(&v).Elem()
f := vv.FieldByName("Hp")
for i := 0; i < AssignTimes; i++ {
f.SetInt(3)
}
}
func TestReflectFindFieldAndAssign(t *testing.T) {
v := data{Hp: 2}
vv := reflect.ValueOf(&v).Elem()
for i := 0; i < AssignTimes; i++ {
vv.FieldByName("Hp").SetInt(3)
}
}
func foo(v int) {
}
const CallTimes = 100000000
func TestNativeCall(t *testing.T) {
for i := 0; i < CallTimes; i++ {
foo(i)
}
}
func TestReflectCall(t *testing.T) {
v := reflect.ValueOf(foo)
for i := 0; i < CallTimes; i++ {
v.Call([]reflect.Value{reflect.ValueOf(2)})
}
}
  性能测试数据
=== RUN TestNativeAssign
— PASS: TestNativeAssign (0.03s)
=== RUN TestReflectAssign
— PASS: TestReflectAssign (0.41s)
=== RUN TestReflectFindFieldAndAssign
— PASS: TestReflectFindFieldAndAssign (9.86s)
=== RUN TestNativeCall
— PASS: TestNativeCall (0.03s)
=== RUN TestReflectCall
— PASS: TestReflectCall (21.46s)