github.com/sohaha/zlsgo@v1.7.13-0.20240501141223-10dd1a906f76/zdi/pre_test.go (about) 1 package zdi_test 2 3 import ( 4 "reflect" 5 "testing" 6 "time" 7 8 "github.com/sohaha/zlsgo" 9 "github.com/sohaha/zlsgo/zdi" 10 "github.com/sohaha/zlsgo/zreflect" 11 ) 12 13 type testFastr func(v1 time.Time, v2 *testSt) string 14 15 func (f testFastr) Invoke(args []interface{}) ([]reflect.Value, error) { 16 s := f(args[0].(time.Time), args[1].(*testSt)) 17 return []reflect.Value{zreflect.ValueOf(s)}, nil 18 } 19 20 type testFastRest func(v1 time.Time, v2 *testSt) string 21 22 func (f testFastRest) Invoke(args []interface{}) ([]interface{}, error) { 23 s := f(args[0].(time.Time), args[1].(*testSt)) 24 return []interface{}{s}, nil 25 } 26 27 func TestFastInvoke(t *testing.T) { 28 tt := zlsgo.NewTest(t) 29 di := zdi.New() 30 31 val := time.Now() 32 override := di.Maps(val, &testSt{Msg: "The is FastInvoke"}) 33 tt.Equal(0, len(override)) 34 35 f := testFastr(func(v1 time.Time, v2 *testSt) string { 36 t.Log(v1, v2) 37 return "yes" 38 }) 39 40 t.Log(zdi.IsPreInvoker(f)) 41 42 invoke, err := di.Invoke(f) 43 t.Log(invoke, err) 44 45 fr := testFastRest(func(v1 time.Time, v2 *testSt) string { 46 t.Log(v1, v2) 47 return "yes" 48 }) 49 50 t.Log(zdi.IsPreInvoker(fr)) 51 52 invoke, err = di.Invoke(fr) 53 t.Log(invoke, err) 54 } 55 56 func BenchmarkFast(b *testing.B) { 57 di := zdi.New() 58 now := time.Now() 59 _ = di.Maps(now, &testSt{Msg: ""}) 60 f := testFastr(func(v1 time.Time, v2 *testSt) string { 61 if v1 != now { 62 b.Error("not equal") 63 b.Fail() 64 } 65 return "yes" 66 }) 67 b.ResetTimer() 68 b.ReportAllocs() 69 for i := 0; i < b.N; i++ { 70 _, err := di.Invoke(f) 71 if err != nil { 72 b.Error("not equal") 73 b.Fail() 74 } 75 } 76 } 77 78 func BenchmarkNoFast(b *testing.B) { 79 di := zdi.New() 80 now := time.Now() 81 _ = di.Maps(now, &testSt{Msg: ""}) 82 f := func(v1 time.Time, v2 *testSt) string { 83 if v1 != now { 84 b.Error("not equal") 85 b.Fail() 86 } 87 return "yes" 88 } 89 for i := 0; i < b.N; i++ { 90 _, err := di.Invoke(f) 91 if err != nil { 92 b.Error("not equal") 93 b.Fail() 94 } 95 } 96 } 97 98 func BenchmarkNoFast2(b *testing.B) { 99 di := zdi.New() 100 now := time.Now() 101 _ = di.Maps(now, &testSt{Msg: ""}) 102 f := func(v1 time.Time, v2 *testSt) string { 103 if v1 != now { 104 b.Error("not equal") 105 b.Fail() 106 } 107 return "yes" 108 } 109 for i := 0; i < b.N; i++ { 110 _, err := di.Invoke(testFastRest(f)) 111 if err != nil { 112 b.Error("not equal") 113 b.Fail() 114 } 115 } 116 }