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