github.com/nyan233/littlerpc@v0.4.6-0.20230316182519-0c8d5c48abaf/core/protocol/message/bench_test.go (about)

     1  package message
     2  
     3  import (
     4  	container2 "github.com/nyan233/littlerpc/core/container"
     5  	"math/rand"
     6  	"sync"
     7  	"testing"
     8  )
     9  
    10  func BenchmarkProtocol(b *testing.B) {
    11  	msg := &Message{
    12  		scope:         [...]uint8{MagicNumber, Call},
    13  		serviceName:   "Hello/Add",
    14  		msgId:         rand.Uint64(),
    15  		MetaData:      container2.NewSliceMap[string, string](10),
    16  		payloadLayout: []uint32{1 << 10, 1 << 11, 1 << 12, 1 << 13},
    17  		payloads:      nil,
    18  	}
    19  	msg.MetaData.Store("Error", "My is Error")
    20  	pool := &sync.Pool{
    21  		New: func() interface{} {
    22  			var tmp container2.Slice[byte] = make([]byte, 0, 128)
    23  			return &tmp
    24  		},
    25  	}
    26  	b.Run("MessageAlloc", func(b *testing.B) {
    27  		b.ReportAllocs()
    28  		for i := 0; i < b.N; i++ {
    29  			_ = New()
    30  		}
    31  	})
    32  	b.Run("ProtocolHeaderMarshal", func(b *testing.B) {
    33  		b.ReportAllocs()
    34  		for i := 0; i < b.N; i++ {
    35  			bp := pool.Get().(*container2.Slice[byte])
    36  			Marshal(msg, bp)
    37  			pool.Put(bp)
    38  		}
    39  	})
    40  	var headerData container2.Slice[byte] = make([]byte, 128)
    41  	Marshal(msg, &headerData)
    42  	b.Run("ProtocolHeaderUnmarshal", func(b *testing.B) {
    43  		b.ReportAllocs()
    44  		for i := 0; i < b.N; i++ {
    45  			ResetMsg(msg, true, false, true, 1024)
    46  			_ = Unmarshal(headerData, msg)
    47  		}
    48  	})
    49  }