github.com/nyan233/littlerpc@v0.4.6-0.20230316182519-0c8d5c48abaf/internal/reflect/struct_type_test.go (about)

     1  package reflect
     2  
     3  import (
     4  	"encoding/json"
     5  	"fmt"
     6  	"reflect"
     7  	"testing"
     8  )
     9  
    10  func TestCreateSliceType(t *testing.T) {
    11  	getTypeInfo(func(k int, v interface{}) {
    12  		t.Run(fmt.Sprintf("CreateNoSliceType-%s", reflect.TypeOf(v).Kind()), func(t *testing.T) {
    13  			for i := 0; i < 10; i++ {
    14  				val := CreateAnyStructOnType(v)
    15  				ComposeStructAnyEface(val, reflect.TypeOf(v))
    16  			}
    17  		})
    18  	})
    19  	getTypeInfo(func(k int, v interface{}) {
    20  		t.Run(fmt.Sprintf("CreateSliceType-%s", reflect.TypeOf(v).Kind()), func(t *testing.T) {
    21  			for i := 0; i < 10; i++ {
    22  				val := CreateAnyStructOnElemType(v)
    23  				ComposeStructAnyEface(val, reflect.TypeOf(v))
    24  			}
    25  		})
    26  	})
    27  }
    28  
    29  func BenchmarkCrateAndJsonUnmarshal(b *testing.B) {
    30  	type Any struct {
    31  		Any interface{}
    32  	}
    33  	const JsonData = `{"Any": 1024}`
    34  	b.Run("No-Reflect-Create", func(b *testing.B) {
    35  		b.ReportAllocs()
    36  		typ := reflect.TypeOf(*new(int64))
    37  		for i := 0; i < b.N; i++ {
    38  			val := CreateAnyStructOnType(*new(int64))
    39  			_ = json.Unmarshal([]byte(JsonData), val)
    40  			_ = ComposeStructAnyEface(val, typ)
    41  		}
    42  	})
    43  	b.Run("Reflect-Create", func(b *testing.B) {
    44  		b.ReportAllocs()
    45  		for i := 0; i < b.N; i++ {
    46  			var any Any
    47  			any.Any = *new(int64)
    48  			_ = json.Unmarshal([]byte(JsonData), &any)
    49  			_ = any.Any
    50  		}
    51  	})
    52  }