network: preallocate buffer for message

```
name            old time/op    new time/op    delta
MessageBytes-8     740ns ± 0%     684ns ± 2%   -7.58%  (p=0.000 n=10+10)

name            old alloc/op   new alloc/op   delta
MessageBytes-8    1.39kB ± 0%    1.20kB ± 0%  -13.79%  (p=0.000 n=10+10)

name            old allocs/op  new allocs/op  delta
MessageBytes-8      11.0 ± 0%      10.0 ± 0%   -9.09%  (p=0.000 n=10+10)
```

Signed-off-by: Evgeniy Stratonikov <evgeniy@nspcc.ru>
This commit is contained in:
Evgeniy Stratonikov 2021-08-06 11:15:50 +03:00
parent dacf025dd9
commit c74de9a579
2 changed files with 33 additions and 0 deletions

View file

@ -182,6 +182,11 @@ func (m *Message) Encode(br *io.BinWriter) error {
if err := m.tryCompressPayload(); err != nil {
return err
}
growSize := 2 + 1 // header + empty payload
if m.compressedPayload != nil {
growSize += 8 + len(m.compressedPayload) // varint + byte-slice
}
br.Grow(growSize)
br.WriteB(byte(m.Flags))
br.WriteB(byte(m.Command))
if m.compressedPayload != nil {

View file

@ -52,6 +52,34 @@ func TestEncodeDecodeVersion(t *testing.T) {
require.NotEqual(t, len(expected.compressedPayload), len(uncompressed))
}
func BenchmarkMessageBytes(b *testing.B) {
// shouldn't try to compress headers payload
ep := &payload.Extensible{
Category: "consensus",
ValidBlockStart: rand.Uint32(),
ValidBlockEnd: rand.Uint32(),
Sender: util.Uint160{},
Data: make([]byte, 300),
Witness: transaction.Witness{
InvocationScript: make([]byte, 33),
VerificationScript: make([]byte, 40),
},
}
random.Fill(ep.Data)
random.Fill(ep.Witness.InvocationScript)
random.Fill(ep.Witness.VerificationScript)
msg := NewMessage(CMDExtensible, ep)
b.ReportAllocs()
b.ResetTimer()
for i := 0; i < b.N; i++ {
_, err := msg.Bytes()
if err != nil {
b.FailNow()
}
}
}
func TestEncodeDecodeHeaders(t *testing.T) {
// shouldn't try to compress headers payload
headers := &payload.Headers{Hdrs: make([]*block.Header, CompressionMinSize)}