1
0
mirror of https://github.com/v2fly/v2ray-core.git synced 2024-09-29 15:26:29 -04:00

Change buffer recycling schedule

This commit is contained in:
V2Ray 2015-10-08 15:28:22 +02:00
parent 9ee73c4f6b
commit 5b7fa17aa6

View File

@ -36,20 +36,18 @@ func (b *Buffer) Len() int {
} }
type bufferPool struct { type bufferPool struct {
chain chan *Buffer chain chan *Buffer
allocator func(*bufferPool) *Buffer allocator func(*bufferPool) *Buffer
minElements int elements2Keep int
maxElements int
} }
func newBufferPool(allocator func(*bufferPool) *Buffer, minElements, maxElements int) *bufferPool { func newBufferPool(allocator func(*bufferPool) *Buffer, elements2Keep, size int) *bufferPool {
pool := &bufferPool{ pool := &bufferPool{
chain: make(chan *Buffer, maxElements*2), chain: make(chan *Buffer, size),
allocator: allocateSmall, allocator: allocateSmall,
minElements: minElements, elements2Keep: elements2Keep,
maxElements: maxElements,
} }
for i := 0; i < minElements; i++ { for i := 0; i < elements2Keep; i++ {
pool.chain <- allocator(pool) pool.chain <- allocator(pool)
} }
go pool.cleanup(time.Tick(1 * time.Second)) go pool.cleanup(time.Tick(1 * time.Second))
@ -79,11 +77,12 @@ func (p *bufferPool) free(buffer *Buffer) {
func (p *bufferPool) cleanup(tick <-chan time.Time) { func (p *bufferPool) cleanup(tick <-chan time.Time) {
for range tick { for range tick {
pSize := len(p.chain) pSize := len(p.chain)
for delta := pSize - p.minElements; delta > 0; delta-- { if pSize > p.elements2Keep {
p.chain <- p.allocator(p)
}
for delta := p.maxElements - pSize; delta > 0; delta-- {
<-p.chain <-p.chain
continue
}
for delta := pSize - p.elements2Keep; delta > 0; delta-- {
p.chain <- p.allocator(p)
} }
} }
} }
@ -97,7 +96,7 @@ func allocateSmall(pool *bufferPool) *Buffer {
return b return b
} }
var smallPool = newBufferPool(allocateSmall, 256, 1024) var smallPool = newBufferPool(allocateSmall, 256, 2048)
func NewBuffer() *Buffer { func NewBuffer() *Buffer {
return smallPool.allocate() return smallPool.allocate()