Avoid 64K allocation on the heap with each Receive

Currently each call to Receive() allocates 64K buffer on the heap
for the data to receive from a netlink socket. This is rather costly
considering that in most cases only fraction of this memory is actually
needed.

A quick fix is to make sure that the large buffer does not "escape" -
i.e. that it is sufficient to have it allocated on the stack.
Then only the prefix of the buffer that was actually used
is copied to the heap.

Fix for issue: #379

Signed-off-by: Milan Lenco <milan.lenco@pantheon.tech>
This commit is contained in:
Milan Lenco 2019-01-02 14:07:05 +01:00 committed by Vish (Ishaya) Abrams
parent 332a6983d9
commit e37f4b431a
2 changed files with 6 additions and 5 deletions

View File

@ -17,7 +17,7 @@ import (
const (
SizeofLinkStats32 = 0x5c
SizeofLinkStats64 = 0xd8
SizeofLinkStats64 = 0xb8
)
const (

View File

@ -622,16 +622,17 @@ func (s *NetlinkSocket) Receive() ([]syscall.NetlinkMessage, error) {
if fd < 0 {
return nil, fmt.Errorf("Receive called on a closed socket")
}
rb := make([]byte, RECEIVE_BUFFER_SIZE)
nr, _, err := unix.Recvfrom(fd, rb, 0)
var rb [RECEIVE_BUFFER_SIZE]byte
nr, _, err := unix.Recvfrom(fd, rb[:], 0)
if err != nil {
return nil, err
}
if nr < unix.NLMSG_HDRLEN {
return nil, fmt.Errorf("Got short response from netlink")
}
rb = rb[:nr]
return syscall.ParseNetlinkMessage(rb)
rb2 := make([]byte, nr)
copy(rb2, rb[:nr])
return syscall.ParseNetlinkMessage(rb2)
}
// SetSendTimeout allows to set a send timeout on the socket