github.com/ipld/go-ipld-prime@v0.21.0/node/tests/marshalBenchmarks.go (about) 1 package tests 2 3 import ( 4 "bytes" 5 "fmt" 6 "strings" 7 "testing" 8 9 "github.com/ipld/go-ipld-prime/codec/json" 10 "github.com/ipld/go-ipld-prime/datamodel" 11 "github.com/ipld/go-ipld-prime/must" 12 "github.com/ipld/go-ipld-prime/node/tests/corpus" 13 ) 14 15 // All of the marshalling and unmarshalling benchmark specs use JSON. 16 // This does mean we're measuring a bunch of stuff that has nothing to do 17 // with the core operations of the Node/NodeBuilder interface. 18 // We do this so that: 19 // - we get a reasonable picture of how much time is spent in the IPLD Data Model 20 // versus how much time is spent in the serialization efforts; 21 // - we can make direct comparisons to the standard library json marshalling 22 // and unmarshalling, thus having a back-of-the-envelope baseline to compare. 23 24 func BenchmarkSpec_Marshal_Map3StrInt(b *testing.B, np datamodel.NodePrototype) { 25 nb := np.NewBuilder() 26 must.NotError(json.Decode(nb, strings.NewReader(`{"whee":1,"woot":2,"waga":3}`))) 27 n := nb.Build() 28 b.ResetTimer() 29 var err error 30 for i := 0; i < b.N; i++ { 31 var buf bytes.Buffer 32 err = json.Encode(n, &buf) 33 sink = buf 34 } 35 if err != nil { 36 panic(err) 37 } 38 } 39 40 func BenchmarkSpec_Marshal_MapNStrMap3StrInt(b *testing.B, np datamodel.NodePrototype) { 41 for _, n := range []int{0, 1, 2, 4, 8, 16, 32} { 42 b.Run(fmt.Sprintf("n=%d", n), func(b *testing.B) { 43 msg := corpus.MapNStrMap3StrInt(n) 44 node := mustNodeFromJsonString(np, msg) 45 b.ResetTimer() 46 47 var buf bytes.Buffer 48 var err error 49 for i := 0; i < b.N; i++ { 50 buf = bytes.Buffer{} 51 err = json.Encode(node, &buf) 52 } 53 54 b.StopTimer() 55 if err != nil { 56 b.Fatalf("encode errored: %s", err) 57 } 58 if buf.String() != msg { 59 b.Fatalf("encode result didn't match corpus") 60 } 61 }) 62 } 63 }