Skip to content

Commit

Permalink
opt: avoid memory allocations when calling readv
Browse files Browse the repository at this point in the history
  • Loading branch information
panjf2000 committed Dec 3, 2021
1 parent 0dcf599 commit 15611b4
Show file tree
Hide file tree
Showing 2 changed files with 6 additions and 2 deletions.
4 changes: 3 additions & 1 deletion pkg/ringbuffer/ring_buffer.go
Original file line number Diff line number Diff line change
Expand Up @@ -40,6 +40,7 @@ var ErrIsEmpty = errors.New("ring-buffer is empty")

// RingBuffer is a circular buffer that implement io.ReaderWriter interface.
type RingBuffer struct {
bs [][]byte
buf []byte
size int
r int // next position to read
Expand All @@ -53,10 +54,11 @@ var EmptyRingBuffer = New(0)
// New returns a new RingBuffer whose buffer has the given size.
func New(size int) *RingBuffer {
if size == 0 {
return &RingBuffer{isEmpty: true}
return &RingBuffer{bs: make([][]byte, 2), isEmpty: true}
}
size = toolkit.CeilToPowerOfTwo(size)
return &RingBuffer{
bs: make([][]byte, 2),
buf: make([]byte, size),
size: size,
isEmpty: true,
Expand Down
4 changes: 3 additions & 1 deletion pkg/ringbuffer/ring_buffer_unix.go
Original file line number Diff line number Diff line change
Expand Up @@ -53,7 +53,9 @@ func (rb *RingBuffer) CopyFromSocket(fd int) (n int, err error) {
}
return
}
n, err = io.Readv(fd, [][]byte{rb.buf[rb.w:], rb.buf[:rb.r]})
rb.bs[0] = rb.buf[rb.w:]
rb.bs[1] = rb.buf[:rb.r]
n, err = io.Readv(fd, rb.bs)
if n > 0 {
rb.w = (rb.w + n) % rb.size
rb.isEmpty = false
Expand Down

0 comments on commit 15611b4

Please sign in to comment.