Commit 2ade7ce2 authored by Steven Allen's avatar Steven Allen

Preallocate pools

1. They're small.
2. We can avoid the lock (major speedup).
3. Better memory locality.
4. Much simpler.
parent ae547a1d
...@@ -40,9 +40,7 @@ const MaxLength = 1 << 32 ...@@ -40,9 +40,7 @@ const MaxLength = 1 << 32
// Pool is a pool to handle cases of reusing elements of varying sizes. // Pool is a pool to handle cases of reusing elements of varying sizes.
// It maintains up to 32 internal pools, for each power of 2 in 0-32. // It maintains up to 32 internal pools, for each power of 2 in 0-32.
type Pool struct { type Pool struct {
small int // the size of the first pool pools [32]sync.Pool // a list of singlePools
pools [32]*sync.Pool // a list of singlePools
sync.Mutex // protecting list
// New is a function that constructs a new element in the pool, with given len // New is a function that constructs a new element in the pool, with given len
New func(len int) interface{} New func(len int) interface{}
...@@ -52,16 +50,7 @@ func (p *Pool) getPool(idx uint32) *sync.Pool { ...@@ -52,16 +50,7 @@ func (p *Pool) getPool(idx uint32) *sync.Pool {
if idx > uint32(len(p.pools)) { if idx > uint32(len(p.pools)) {
panic(fmt.Errorf("index too large: %d", idx)) panic(fmt.Errorf("index too large: %d", idx))
} }
return &p.pools[idx]
p.Lock()
defer p.Unlock()
sp := p.pools[idx]
if sp == nil {
sp = new(sync.Pool)
p.pools[idx] = sp
}
return sp
} }
// Get selects an arbitrary item from the Pool, removes it from the Pool, // Get selects an arbitrary item from the Pool, removes it from the Pool,
......
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