1
0
mirror of https://github.com/v2fly/v2ray-core.git synced 2026-06-16 07:49:56 -04:00

refine buffer allocation

This commit is contained in:
Darien Raymond
2018-03-11 23:06:04 +01:00
parent 5eac607087
commit f97e6fa3d2
7 changed files with 72 additions and 74 deletions

View File

@@ -4,39 +4,29 @@ import (
"sync"
)
// Pool provides functionality to generate and recycle buffers on demand.
type Pool struct {
allocator *sync.Pool
}
// NewPool creates a SyncPool with given buffer size.
func NewPool(bufferSize uint32) *Pool {
pool := &Pool{
allocator: &sync.Pool{
New: func() interface{} { return make([]byte, bufferSize) },
},
}
return pool
}
// Allocate either returns a unused buffer from the pool, or generates a new one from system.
func (p *Pool) Allocate() *Buffer {
return &Buffer{
v: p.allocator.Get().([]byte),
pool: p,
}
}
// // Free recycles the given buffer.
func (p *Pool) Free(buffer *Buffer) {
if buffer.v != nil {
p.allocator.Put(buffer.v)
}
}
const (
// Size of a regular buffer.
Size = 2 * 1024
)
var mediumPool = NewPool(Size)
func createAllocFunc(size uint32) func() interface{} {
return func() interface{} {
return make([]byte, size)
}
}
var pool2k = &sync.Pool{
New: createAllocFunc(2 * 1024),
}
var pool8k = &sync.Pool{
New: createAllocFunc(8 * 1024),
}
var pool64k = &sync.Pool{
New: createAllocFunc(64 * 1024),
}
var pool128k = &sync.Pool{
New: createAllocFunc(128 * 1024),
}