Skip to content

Commit

Permalink
Reduce RingBuffer heap allocation
Browse files Browse the repository at this point in the history
  • Loading branch information
chrisxue815 committed Aug 29, 2019
1 parent f07cbe3 commit 827210d
Show file tree
Hide file tree
Showing 2 changed files with 10 additions and 4 deletions.
8 changes: 4 additions & 4 deletions queue/ring.go
Original file line number Diff line number Diff line change
Expand Up @@ -41,7 +41,7 @@ type node struct {
data interface{}
}

type nodes []*node
type nodes []node

// RingBuffer is a MPMC buffer that achieves threadsafety with CAS operations
// only. A put on full or get on empty call will block until an item
Expand All @@ -64,7 +64,7 @@ func (rb *RingBuffer) init(size uint64) {
size = roundUp(size)
rb.nodes = make(nodes, size)
for i := uint64(0); i < size; i++ {
rb.nodes[i] = &node{position: i}
rb.nodes[i] = node{position: i}
}
rb.mask = size - 1 // so we don't have to do this with every put/get operation
}
Expand Down Expand Up @@ -93,7 +93,7 @@ L:
return false, ErrDisposed
}

n = rb.nodes[pos&rb.mask]
n = &rb.nodes[pos&rb.mask]
seq := atomic.LoadUint64(&n.position)
switch dif := seq - pos; {
case dif == 0:
Expand Down Expand Up @@ -146,7 +146,7 @@ L:
return nil, ErrDisposed
}

n = rb.nodes[pos&rb.mask]
n = &rb.nodes[pos&rb.mask]
seq := atomic.LoadUint64(&n.position)
switch dif := seq - (pos + 1); {
case dif == 0:
Expand Down
6 changes: 6 additions & 0 deletions queue/ring_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -396,3 +396,9 @@ func BenchmarkRBGet(b *testing.B) {
rb.Get()
}
}

func BenchmarkRBAllocation(b *testing.B) {
for i := 0; i < b.N; i++ {
NewRingBuffer(1024)
}
}

0 comments on commit 827210d

Please sign in to comment.