github.com/cloudwego/dynamicgo@v0.2.6-0.20240519101509-707f41b6b834/conv/j2p/conv_timing_test.go (about) 1 package j2p 2 3 import ( 4 "context" 5 "encoding/json" 6 "testing" 7 8 "github.com/cloudwego/dynamicgo/conv" 9 "github.com/cloudwego/dynamicgo/testdata/kitex_gen/pb/example2" 10 "github.com/stretchr/testify/require" 11 goprotowire "google.golang.org/protobuf/encoding/protowire" 12 ) 13 14 func BenchmarkConvJSON2Protobuf_DynamicGo(b *testing.B) { 15 desc := getExampleDesc() 16 data := getExampleData() 17 cv := NewBinaryConv(conv.Options{}) 18 ctx := context.Background() 19 // dynamicgo exec json2pb 20 out, err := cv.Do(ctx, desc, data) 21 require.Nil(b, err) 22 23 // unmarshal json to get pbObj 24 exp := example2.ExampleReq{} 25 err = json.Unmarshal(data, &exp) 26 require.Nil(b, err) 27 act := example2.ExampleReq{} 28 l := 0 29 dataLen := len(out) 30 for l < dataLen { 31 id, wtyp, tagLen := goprotowire.ConsumeTag(out) 32 if tagLen < 0 { 33 b.Fatal("error pb data format") 34 } 35 l += tagLen 36 out = out[tagLen:] 37 offset, err := act.FastRead(out, int8(wtyp), int32(id)) 38 require.Nil(b, err) 39 out = out[offset:] 40 l += offset 41 } 42 require.Equal(b, exp, act) 43 44 b.ResetTimer() 45 for i := 0; i < b.N; i++ { 46 out = out[:0] 47 _ = cv.DoInto(ctx, desc, data, &out) 48 } 49 } 50 51 func BenchmarkConvJSON2Protobuf_Parallel_DynamicGo(b *testing.B) { 52 desc := getExampleDesc() 53 data := getExampleData() 54 cv := NewBinaryConv(conv.Options{}) 55 ctx := context.Background() 56 // dynamicgo exec json2pb 57 out, err := cv.Do(ctx, desc, data) 58 require.Nil(b, err) 59 60 // unmarshal json to get pbObj 61 exp := example2.ExampleReq{} 62 err = json.Unmarshal(data, &exp) 63 require.Nil(b, err) 64 act := example2.ExampleReq{} 65 l := 0 66 dataLen := len(out) 67 for l < dataLen { 68 id, wtyp, tagLen := goprotowire.ConsumeTag(out) 69 if tagLen < 0 { 70 b.Fatal("error pb data format") 71 } 72 l += tagLen 73 out = out[tagLen:] 74 offset, err := act.FastRead(out, int8(wtyp), int32(id)) 75 require.Nil(b, err) 76 out = out[offset:] 77 l += offset 78 } 79 require.Equal(b, exp, act) 80 81 b.ResetTimer() 82 b.RunParallel(func(b *testing.PB) { 83 buf := make([]byte, 0, dataLen) 84 for b.Next() { 85 buf := buf[:0] 86 _ = cv.DoInto(ctx, desc, data, &buf) 87 } 88 }) 89 }