-
Notifications
You must be signed in to change notification settings - Fork 94
/
Copy pathbufferpool.go
53 lines (42 loc) · 830 Bytes
/
bufferpool.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
package hero
import (
"bytes"
"sync"
)
const buffSize = 10000
var defaultPool *pool
func init() {
defaultPool = newPool()
}
type pool struct {
pool *sync.Pool
ch chan *bytes.Buffer
}
func newPool() *pool {
p := &pool{
pool: &sync.Pool{
New: func() interface{} {
return new(bytes.Buffer)
},
},
ch: make(chan *bytes.Buffer, buffSize),
}
// It's faster with unused channel buffer in go1.7.
// TODO: need removed?
for i := 0; i < buffSize; i++ {
p.ch <- new(bytes.Buffer)
}
return p
}
// GetBuffer returns a *bytes.Buffer from sync.Pool.
func GetBuffer() *bytes.Buffer {
return defaultPool.pool.Get().(*bytes.Buffer)
}
// PutBuffer puts a *bytes.Buffer to the sync.Pool.
func PutBuffer(buffer *bytes.Buffer) {
if buffer == nil {
return
}
buffer.Reset()
defaultPool.pool.Put(buffer)
}