github.com/volts-dev/volts@v0.0.0-20240120094013-5e9c65924106/internal/test/router/handler_call_benchmark_test.go (about)

     1  package router
     2  
     3  import (
     4  	"reflect"
     5  	"testing"
     6  )
     7  
     8  func initCall(obj interface{}) (reflect.Value, func(...interface{}) string, iCtrl, func(...interface{}) string) {
     9  	objVval := reflect.ValueOf(obj)
    10  	funVal := objVval.MethodByName("String")
    11  	var wrap iwrapper
    12  	wrap = &wrapper{
    13  		Func: funVal.Interface().(func(...interface{}) string),
    14  	}
    15  
    16  	v := reflect.ValueOf(wrap)
    17  	vv := v.Interface().(iwrapper)
    18  	return funVal, funVal.Interface().(func(s ...interface{}) string), objVval.Interface().(iCtrl), vv.String
    19  }
    20  
    21  func BenchmarkHandlerDirectCall(b *testing.B) {
    22  	obj := &ctrl{Name: "111"}
    23  	initCall(obj)
    24  	for n := 0; n < b.N; n++ {
    25  		obj.String()
    26  	}
    27  }
    28  
    29  func BenchmarkHandlerReflectCall(b *testing.B) {
    30  	obj := &ctrl{Name: "111"}
    31  	fnVal, _, _, _ := initCall(obj)
    32  	for n := 0; n < b.N; n++ {
    33  		fnVal.Call(nil)
    34  	}
    35  }
    36  
    37  func BenchmarkHandlerReflectInterfaceStruct(b *testing.B) {
    38  	obj := &ctrl{Name: "111"}
    39  	_, _, o, _ := initCall(obj)
    40  	for n := 0; n < b.N; n++ {
    41  		o.String()
    42  	}
    43  }
    44  
    45  func BenchmarkHandlerReflectInterfaceFunc(b *testing.B) {
    46  	obj := &ctrl{Name: "111"}
    47  	_, fn, _, _ := initCall(obj)
    48  	for n := 0; n < b.N; n++ {
    49  		fn()
    50  	}
    51  }
    52  
    53  func BenchmarkHandlerReflectInterfaceFunc2(b *testing.B) {
    54  	obj := &ctrl{Name: "111"}
    55  	_, _, _, fn := initCall(obj)
    56  
    57  	for n := 0; n < b.N; n++ {
    58  		fn()
    59  	}
    60  }