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

Avoid extra allocation using buffer pools #370

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
15 changes: 13 additions & 2 deletions buffer/pool.go
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ import (
"io"
"net"
"sync"
"unsafe"
)

// PoolConfig contains configuration for the allocation and reuse strategy.
Expand Down Expand Up @@ -47,17 +48,27 @@ func putBuf(buf []byte) {
return
}
if c := buffers[size]; c != nil {
c.Put(buf[:0])
// Save un unsafe pointer to the array instead of the slice to
// avoid an extra allocation.
// We don't care about the length and we know the capability so
// we don't need to save anything else.
c.Put(unsafe.Pointer(&buf[:1][0]))
}
}

const maxArraySize = uint((uint64(1) << 50 - 1) & uint64(^uint(0) >> 1))

// getBuf gets a chunk from reuse pool or creates a new one if reuse failed.
func getBuf(size int) []byte {
if size >= config.PooledSize {
if c := buffers[size]; c != nil {
v := c.Get()
if v != nil {
return v.([]byte)
// Recreate back the original slice.
// Get back the array and add length and capability.
// Limiting the array to the proper capability will make this
// safe.
return (*[maxArraySize]byte)(v.(unsafe.Pointer))[:0:size]
}
}
}
Expand Down