From ee3b8204de5673aa3a68f0f546c6c6d83b41b750 Mon Sep 17 00:00:00 2001 From: gobwas Date: Wed, 24 Feb 2016 19:49:44 +0300 Subject: [PATCH] use sync.pool --- match/segments.go | 73 +++-------------------------------------------- 1 file changed, 4 insertions(+), 69 deletions(-) diff --git a/match/segments.go b/match/segments.go index 7d12850..5406f37 100644 --- a/match/segments.go +++ b/match/segments.go @@ -9,9 +9,7 @@ type SomePool interface { Put([]int) } -var segmentsPools [1024]SomePool - -//var segmentsPools [1024]*sync.Pool +var segmentsPools [1024]sync.Pool func toPowerOfTwo(v int) int { v-- @@ -56,15 +54,9 @@ const ( func init() { for i := cacheToAndHigher; i >= cacheFrom; i >>= 1 { func(i int) { - // segmentsPools[i-1] = &sync.Pool{New: func() interface{} { - // return make([]int, 0, i) - // }} - // segmentsPools[i-1] = newChanPool(func() []int { - // return make([]int, 0, i) - // }) - segmentsPools[i-1] = newSyncPool(func() []int { + segmentsPools[i-1] = sync.Pool{New: func() interface{} { return make([]int, 0, i) - }) + }} }(i) } } @@ -88,8 +80,7 @@ func acquireSegments(c int) []int { return make([]int, 0, c) } - // return segmentsPools[getTableIndex(c)].Get().([]int)[:0] - return segmentsPools[getTableIndex(c)].Get() + return segmentsPools[getTableIndex(c)].Get().([]int)[:0] } func releaseSegments(s []int) { @@ -103,59 +94,3 @@ func releaseSegments(s []int) { segmentsPools[getTableIndex(c)].Put(s) } - -type maker func() []int - -type syncPool struct { - new maker - pool sync.Pool -} - -func newSyncPool(m maker) *syncPool { - return &syncPool{ - new: m, - pool: sync.Pool{New: func() interface{} { - return m() - }}, - } -} - -func (s *syncPool) Get() []int { - return s.pool.Get().([]int)[:0] -} - -func (s *syncPool) Put(x []int) { - s.pool.Put(x) -} - -type chanPool struct { - pool chan []int - new maker - index int -} - -func newChanPool(m maker) *chanPool { - return &chanPool{ - pool: make(chan []int, 16), - new: m, - } -} - -func (c *chanPool) Get() []int { - select { - case s := <-c.pool: - return s[:0] - default: - // pool is empty - return c.new() - } -} - -func (c *chanPool) Put(s []int) { - select { - case c.pool <- s: - // ok - default: - // pool is full - } -}