Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Reduce RingBuffer heap allocation #205

Merged
merged 1 commit into from
Mar 2, 2020
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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)
}
}