Skip to content

Commit

Permalink
Only create RawConn.Write callback once
Browse files Browse the repository at this point in the history
This saves an allocation on every call.

#1481
  • Loading branch information
jackc committed Jan 28, 2023
1 parent 42a4719 commit 2c7d86a
Show file tree
Hide file tree
Showing 2 changed files with 13 additions and 8 deletions.
9 changes: 5 additions & 4 deletions internal/nbconn/nbconn.go
Original file line number Diff line number Diff line change
Expand Up @@ -73,10 +73,11 @@ type NetConn struct {

readFlushLock sync.Mutex
// non-blocking writes with syscall.RawConn are done with a callback function. By using these fields instead of the
// callback functions closure to pass the buf argument and receive the n and err results we avoid some allocations.
nonblockWriteBuf []byte
nonblockWriteErr error
nonblockWriteN int
// callback functions closure to pass the buf argument and receive the n and err results we avoid some allocations.
nonblockWriteFunc func(fd uintptr) (done bool)
nonblockWriteBuf []byte
nonblockWriteErr error
nonblockWriteN int

readDeadlineLock sync.Mutex
readDeadline time.Time
Expand Down
12 changes: 8 additions & 4 deletions internal/nbconn/nbconn_real_non_block.go
Original file line number Diff line number Diff line change
Expand Up @@ -12,13 +12,17 @@ import (

// realNonblockingWrite does a non-blocking write. readFlushLock must already be held.
func (c *NetConn) realNonblockingWrite(b []byte) (n int, err error) {
if c.nonblockWriteFunc == nil {
c.nonblockWriteFunc = func(fd uintptr) (done bool) {
c.nonblockWriteN, c.nonblockWriteErr = syscall.Write(int(fd), c.nonblockWriteBuf)
return true
}
}
c.nonblockWriteBuf = b
c.nonblockWriteN = 0
c.nonblockWriteErr = nil
err = c.rawConn.Write(func(fd uintptr) (done bool) {
c.nonblockWriteN, c.nonblockWriteErr = syscall.Write(int(fd), c.nonblockWriteBuf)
return true
})

err = c.rawConn.Write(c.nonblockWriteFunc)
n = c.nonblockWriteN
if err == nil && c.nonblockWriteErr != nil {
if errors.Is(c.nonblockWriteErr, syscall.EWOULDBLOCK) {
Expand Down

0 comments on commit 2c7d86a

Please sign in to comment.