github.com/xhebox/bstruct@v0.0.0-20221115052913-86d4d6d98866/example/bench_test.go (about) 1 package main 2 3 import ( 4 "encoding/json" 5 "testing" 6 7 "github.com/stretchr/testify/require" 8 "github.com/xhebox/bstruct" 9 ) 10 11 func makeData(b *testing.B) []byte { 12 f := &Struct1{} 13 wt := bstruct.NewWriter() 14 f.Encode(wt) 15 return wt.Data() 16 } 17 18 func TestAff(t *testing.T) { 19 f := &Struct1{ 20 B: nil, 21 F: true, 22 D: "gg", 23 G: []string{ 24 "1", 25 "3", 26 "154", 27 }, 28 E: Slice1{ 29 {E: "1"}, 30 }, 31 } 32 g := &Struct1{} 33 t.Logf("%+v\n%+v\n", f, g) 34 35 wt := bstruct.NewWriter() 36 f.Encode(wt) 37 rd := bstruct.NewReader(wt.Data()) 38 g.Decode(rd) 39 require.Equal(t, f, g) 40 t.Logf("%+v\n%+v\n", f, g) 41 } 42 43 func BenchmarkEncode(b *testing.B) { 44 f := &Struct1{ 45 G: []string{ 46 "1", 47 "3", 48 "154", 49 }, 50 } 51 b.ReportAllocs() 52 b.ResetTimer() 53 for i := 0; i < b.N; i++ { 54 wt := bstruct.NewWriter() 55 f.Encode(wt) 56 } 57 } 58 59 func BenchmarkMarshal(b *testing.B) { 60 f := &Struct1{ 61 G: []string{ 62 "1", 63 "3", 64 "154", 65 }, 66 } 67 b.ReportAllocs() 68 b.ResetTimer() 69 for i := 0; i < b.N; i++ { 70 _, err := json.Marshal(f) 71 require.NoError(b, err) 72 } 73 } 74 75 func BenchmarkDecode(b *testing.B) { 76 f := &Struct1{ 77 G: []string{ 78 "1", 79 "3", 80 "154", 81 }, 82 } 83 wt := bstruct.NewWriter() 84 f.Encode(wt) 85 b.ReportAllocs() 86 b.ResetTimer() 87 for i := 0; i < b.N; i++ { 88 rd := bstruct.NewReader(wt.Data()) 89 f.Decode(rd) 90 } 91 } 92 93 func BenchmarkUnmarshal(b *testing.B) { 94 f := &Struct1{ 95 G: []string{ 96 "1", 97 "3", 98 "154", 99 }, 100 } 101 data, err := json.Marshal(f) 102 require.NoError(b, err) 103 b.ReportAllocs() 104 b.ResetTimer() 105 for i := 0; i < b.N; i++ { 106 err = json.Unmarshal(data, f) 107 require.NoError(b, err) 108 } 109 }