github.com/vmware/govmomi@v0.51.0/vim25/types/json_bench_test.go (about)

     1  // © Broadcom. All Rights Reserved.
     2  // The term “Broadcom” refers to Broadcom Inc. and/or its subsidiaries.
     3  // SPDX-License-Identifier: Apache-2.0
     4  
     5  package types
     6  
     7  import (
     8  	"bytes"
     9  	"os"
    10  	"testing"
    11  
    12  	"github.com/vmware/govmomi/vim25/json"
    13  )
    14  
    15  // BenchmarkDecodeVirtualMachineConfigInfo illustrates the performance
    16  // difference between decoding a large vminfo object when the type
    17  // discriminator is the first property in the object versus the last
    18  // property.
    19  func BenchmarkDecodeVirtualMachineConfigInfo(b *testing.B) {
    20  
    21  	testCases := []struct {
    22  		name string
    23  		path string
    24  	}{
    25  		{
    26  			name: "vm info w type name first",
    27  			path: "./testdata/vminfo.json",
    28  		},
    29  		{
    30  			name: "vm info w type name last",
    31  			path: "./testdata/vminfo-typename-at-end.json",
    32  		},
    33  	}
    34  
    35  	for _, tc := range testCases {
    36  		tc := tc // capture the range variable
    37  		b.Run(tc.name, func(b *testing.B) {
    38  			buf, err := os.ReadFile(tc.path)
    39  			if err != nil {
    40  				b.Fatal(err)
    41  			}
    42  
    43  			b.ResetTimer()
    44  
    45  			for i := 0; i < b.N; i++ {
    46  
    47  				dec := json.NewDecoder(bytes.NewReader(buf))
    48  				dec.SetDiscriminator(
    49  					"_typeName", "_value",
    50  					json.DiscriminatorToTypeFunc(TypeFunc()),
    51  				)
    52  
    53  				var obj any
    54  				if err := dec.Decode(&obj); err != nil {
    55  					b.Fatal(err)
    56  				}
    57  			}
    58  		})
    59  	}
    60  }