Skip to content

Commit

Permalink
conn: reuse memory in Receive()
Browse files Browse the repository at this point in the history
Use sync.Pool to reuse memory to receive messages

Signed-off-by: Florian Lehner <dev@der-flo.net>
  • Loading branch information
florianl committed Jun 11, 2024
1 parent 13a521f commit 2aa3dbc
Showing 1 changed file with 18 additions and 3 deletions.
21 changes: 18 additions & 3 deletions conn_linux.go
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ package netlink
import (
"context"
"os"
"sync"
"syscall"
"time"
"unsafe"
Expand All @@ -19,7 +20,8 @@ var _ Socket = &conn{}

// A conn is the Linux implementation of a netlink sockets connection.
type conn struct {
s *socket.Conn
s *socket.Conn
bufPool sync.Pool
}

// dial is the entry point for Dial. dial opens a netlink socket using
Expand Down Expand Up @@ -70,7 +72,15 @@ func newConn(s *socket.Conn, config *Config) (*conn, uint32, error) {
return nil, 0, err
}

c := &conn{s: s}
c := &conn{
s: s,
bufPool: sync.Pool{
New: func() interface{} {
b := make([]byte, 0, os.Getpagesize())
return &b
},
},
}
if config.Strict {
// The caller has requested the strict option set. Historically we have
// recommended checking for ENOPROTOOPT if the kernel does not support
Expand Down Expand Up @@ -121,7 +131,12 @@ func (c *conn) Send(m Message) error {

// Receive receives one or more Messages from netlink.
func (c *conn) Receive() ([]Message, error) {
b := make([]byte, os.Getpagesize())
bufPtr := c.bufPool.Get().(*[]byte)
b := (*bufPtr)[:os.Getpagesize()]
defer func() {
c.bufPool.Put(bufPtr)
}()

for {
// Peek at the buffer to see how many bytes are available.
//
Expand Down

0 comments on commit 2aa3dbc

Please sign in to comment.