Commit a57121fa authored by huiren's avatar huiren Committed by 望哥

bytes_pools with buf ptr (#19)

parent e1a65e20
...@@ -40,7 +40,8 @@ func NewBytesPool(slotSize []int) *BytesPool { ...@@ -40,7 +40,8 @@ func NewBytesPool(slotSize []int) *BytesPool {
for i, size := range bp.sizes { for i, size := range bp.sizes {
size := size size := size
bp.slots[i] = sync.Pool{New: func() interface{} { bp.slots[i] = sync.Pool{New: func() interface{} {
return make([]byte, 0, size) buf := make([]byte, 0, size)
return &buf
}} }}
} }
return bp return bp
...@@ -61,28 +62,31 @@ func (bp *BytesPool) findIndex(size int) int { ...@@ -61,28 +62,31 @@ func (bp *BytesPool) findIndex(size int) int {
} }
// AcquireBytes get specific make([]byte, 0, size) // AcquireBytes get specific make([]byte, 0, size)
func (bp *BytesPool) AcquireBytes(size int) []byte { func (bp *BytesPool) AcquireBytes(size int) *[]byte {
idx := bp.findIndex(size) idx := bp.findIndex(size)
if idx >= bp.length { if idx >= bp.length {
return make([]byte, 0, size) buf := make([]byte, 0, size)
return &buf
} }
return bp.slots[idx].Get().([]byte)[:size] bufp := bp.slots[idx].Get().(*[]byte)
buf := (*bufp)[:size]
return &buf
} }
// ReleaseBytes ... // ReleaseBytes ...
func (bp *BytesPool) ReleaseBytes(buf []byte) { func (bp *BytesPool) ReleaseBytes(bufp *[]byte) {
bufCap := cap(buf) bufCap := cap(*bufp)
idx := bp.findIndex(bufCap) idx := bp.findIndex(bufCap)
if idx >= bp.length || bp.sizes[idx] != bufCap { if idx >= bp.length || bp.sizes[idx] != bufCap {
return return
} }
bp.slots[idx].Put(buf) bp.slots[idx].Put(bufp)
} }
// AcquireBytes called by defaultBytesPool // AcquireBytes called by defaultBytesPool
func AcquireBytes(size int) []byte { return defaultBytesPool.AcquireBytes(size) } func AcquireBytes(size int) *[]byte { return defaultBytesPool.AcquireBytes(size) }
// ReleaseBytes called by defaultBytesPool // ReleaseBytes called by defaultBytesPool
func ReleaseBytes(buf []byte) { defaultBytesPool.ReleaseBytes(buf) } func ReleaseBytes(bufp *[]byte) { defaultBytesPool.ReleaseBytes(bufp) }
...@@ -52,13 +52,12 @@ func NewSlicePool() *SlicePool { ...@@ -52,13 +52,12 @@ func NewSlicePool() *SlicePool {
// Get returns *[]byte from SlicePool // Get returns *[]byte from SlicePool
func (p *SlicePool) Get(size int) *[]byte { func (p *SlicePool) Get(size int) *[]byte {
b := p.AcquireBytes(size) return p.AcquireBytes(size)
return &b
} }
// Put returns *[]byte to SlicePool // Put returns *[]byte to SlicePool
func (p *SlicePool) Put(buf *[]byte) { func (p *SlicePool) Put(bufp *[]byte) {
p.ReleaseBytes(*buf) p.ReleaseBytes(bufp)
} }
// GetBytes returns *[]byte from SlicePool // GetBytes returns *[]byte from SlicePool
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment