mirror of
https://github.com/v2fly/v2ray-core.git
synced 2024-10-02 00:36:03 -04:00
leverage sync.Pool for allocation boost
This commit is contained in:
parent
4773a8f4ae
commit
e0b56528fc
@ -1,5 +1,9 @@
|
|||||||
package alloc
|
package alloc
|
||||||
|
|
||||||
|
import (
|
||||||
|
"sync"
|
||||||
|
)
|
||||||
|
|
||||||
// Buffer is a recyclable allocation of a byte array. Buffer.Release() recycles
|
// Buffer is a recyclable allocation of a byte array. Buffer.Release() recycles
|
||||||
// the buffer into an internal buffer pool, in order to recreate a buffer more
|
// the buffer into an internal buffer pool, in order to recreate a buffer more
|
||||||
// quickly.
|
// quickly.
|
||||||
@ -69,15 +73,16 @@ func (b *Buffer) Write(data []byte) (int, error) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
type bufferPool struct {
|
type bufferPool struct {
|
||||||
chain chan []byte
|
chain chan []byte
|
||||||
bufferSize int
|
allocator *sync.Pool
|
||||||
buffers2Keep int
|
|
||||||
}
|
}
|
||||||
|
|
||||||
func newBufferPool(bufferSize, poolSize int) *bufferPool {
|
func newBufferPool(bufferSize, poolSize int) *bufferPool {
|
||||||
pool := &bufferPool{
|
pool := &bufferPool{
|
||||||
chain: make(chan []byte, poolSize),
|
chain: make(chan []byte, poolSize),
|
||||||
bufferSize: bufferSize,
|
allocator: &sync.Pool{
|
||||||
|
New: func() interface{} { return make([]byte, bufferSize) },
|
||||||
|
},
|
||||||
}
|
}
|
||||||
for i := 0; i < poolSize; i++ {
|
for i := 0; i < poolSize; i++ {
|
||||||
pool.chain <- make([]byte, bufferSize)
|
pool.chain <- make([]byte, bufferSize)
|
||||||
@ -90,7 +95,7 @@ func (p *bufferPool) allocate() *Buffer {
|
|||||||
select {
|
select {
|
||||||
case b = <-p.chain:
|
case b = <-p.chain:
|
||||||
default:
|
default:
|
||||||
b = make([]byte, p.bufferSize)
|
b = p.allocator.Get().([]byte)
|
||||||
}
|
}
|
||||||
return &Buffer{
|
return &Buffer{
|
||||||
head: b,
|
head: b,
|
||||||
@ -103,6 +108,7 @@ func (p *bufferPool) free(buffer *Buffer) {
|
|||||||
select {
|
select {
|
||||||
case p.chain <- buffer.head:
|
case p.chain <- buffer.head:
|
||||||
default:
|
default:
|
||||||
|
p.allocator.Put(buffer.head)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
Loading…
Reference in New Issue
Block a user