-
Notifications
You must be signed in to change notification settings - Fork 11
/
Copy pathpool_test.go
79 lines (66 loc) · 1.27 KB
/
pool_test.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
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
package main
import (
"bytes"
"sync"
"testing"
)
type ChannelBufferPool struct {
c chan *bytes.Buffer
n int
}
func NewChannelBufferPool(size, n int) (bp *ChannelBufferPool) {
return &ChannelBufferPool{
c: make(chan *bytes.Buffer, size),
n: n,
}
}
func (p *ChannelBufferPool) Get() (b *bytes.Buffer) {
select {
case b = <-p.c:
default:
b = bytes.NewBuffer(make([]byte, 0, p.n))
}
return
}
func (p *ChannelBufferPool) Put(b *bytes.Buffer) {
b.Reset()
select {
case p.c <- b:
default:
}
}
func BenchmarkAllocateBufferNoPool(b *testing.B) {
b.RunParallel(func(pb *testing.PB) {
for pb.Next() {
buf := bytes.NewBuffer(make([]byte, 0, 256))
buf.WriteString("gotta catch 'em all")
}
})
}
func BenchmarkChannelBufferPool(b *testing.B) {
p := NewChannelBufferPool(1, 256)
b.ResetTimer()
b.RunParallel(func(pb *testing.PB) {
for pb.Next() {
buf := p.Get()
buf.Reset()
buf.WriteString("gotta catch 'em all")
p.Put(buf)
}
})
}
func BenchmarkSyncBufferPool(b *testing.B) {
var p = sync.Pool{
New: func() interface{} {
return bytes.NewBuffer(make([]byte, 0, 256))
},
}
b.RunParallel(func(pb *testing.PB) {
for pb.Next() {
buf := p.Get().(*bytes.Buffer)
buf.Reset()
buf.WriteString("gotta catch 'em all")
p.Put(buf)
}
})
}