Alexander Yastrebov
|
264889f0bb
|
device: optimize message encoding
Optimize message encoding by eliminating binary.Write (which internally
uses reflection) in favour of hand-rolled encoding.
This is companion to 9e7529c3d2.
Synthetic benchmark:
var packetSink []byte
func BenchmarkMessageInitiationMarshal(b *testing.B) {
var msg MessageInitiation
b.Run("binary.Write", func(b *testing.B) {
b.ReportAllocs()
for range b.N {
var buf [MessageInitiationSize]byte
writer := bytes.NewBuffer(buf[:0])
_ = binary.Write(writer, binary.LittleEndian, msg)
packetSink = writer.Bytes()
}
})
b.Run("binary.Encode", func(b *testing.B) {
b.ReportAllocs()
for range b.N {
packet := make([]byte, MessageInitiationSize)
_, _ = binary.Encode(packet, binary.LittleEndian, msg)
packetSink = packet
}
})
b.Run("marshal", func(b *testing.B) {
b.ReportAllocs()
for range b.N {
packet := make([]byte, MessageInitiationSize)
_ = msg.marshal(packet)
packetSink = packet
}
})
}
Results:
│ - │
│ sec/op │
MessageInitiationMarshal/binary.Write-8 1.337µ ± 0%
MessageInitiationMarshal/binary.Encode-8 1.242µ ± 0%
MessageInitiationMarshal/marshal-8 53.05n ± 1%
│ - │
│ B/op │
MessageInitiationMarshal/binary.Write-8 368.0 ± 0%
MessageInitiationMarshal/binary.Encode-8 160.0 ± 0%
MessageInitiationMarshal/marshal-8 160.0 ± 0%
│ - │
│ allocs/op │
MessageInitiationMarshal/binary.Write-8 3.000 ± 0%
MessageInitiationMarshal/binary.Encode-8 1.000 ± 0%
MessageInitiationMarshal/marshal-8 1.000 ± 0%
Signed-off-by: Alexander Yastrebov <[email protected]>
Signed-off-by: Jason A. Donenfeld <[email protected]>
|
2025-05-21 00:09:36 +02:00 |
|
Alexander Yastrebov
|
9e7529c3d2
|
device: reduce RoutineHandshake allocations
Reduce allocations by eliminating byte reader, hand-rolled decoding and
reusing message structs.
Synthetic benchmark:
var msgSink MessageInitiation
func BenchmarkMessageInitiationUnmarshal(b *testing.B) {
packet := make([]byte, MessageInitiationSize)
reader := bytes.NewReader(packet)
err := binary.Read(reader, binary.LittleEndian, &msgSink)
if err != nil {
b.Fatal(err)
}
b.Run("binary.Read", func(b *testing.B) {
b.ReportAllocs()
for range b.N {
reader := bytes.NewReader(packet)
_ = binary.Read(reader, binary.LittleEndian, &msgSink)
}
})
b.Run("unmarshal", func(b *testing.B) {
b.ReportAllocs()
for range b.N {
_ = msgSink.unmarshal(packet)
}
})
}
Results:
│ - │
│ sec/op │
MessageInitiationUnmarshal/binary.Read-8 1.508µ ± 2%
MessageInitiationUnmarshal/unmarshal-8 12.66n ± 2%
│ - │
│ B/op │
MessageInitiationUnmarshal/binary.Read-8 208.0 ± 0%
MessageInitiationUnmarshal/unmarshal-8 0.000 ± 0%
│ - │
│ allocs/op │
MessageInitiationUnmarshal/binary.Read-8 2.000 ± 0%
MessageInitiationUnmarshal/unmarshal-8 0.000 ± 0%
Signed-off-by: Alexander Yastrebov <[email protected]>
Signed-off-by: Jason A. Donenfeld <[email protected]>
|
2025-05-15 16:42:06 +02:00 |
|