Skip to content

Commit

Permalink
添加pool benchmark
Browse files Browse the repository at this point in the history
  • Loading branch information
lintanghui committed Mar 25, 2016
1 parent d53fb73 commit bbfb859
Showing 1 changed file with 47 additions and 0 deletions.
47 changes: 47 additions & 0 deletions chapter16/16.01.md
Original file line number Diff line number Diff line change
Expand Up @@ -118,6 +118,53 @@ func (ss *ServerList) PickServer(key string) (net.Addr, error) {

答案是不会的,sync.Pool的回收是有的,它是在系统自动GC的时候,触发pool.go中的poolCleanup函数。


连接池性能测试

```golang
package main

import (
"sync"
"testing"
)

var bytePool = sync.Pool{
New: newPool,
}

func newPool() interface{} {
b := make([]byte, 1024)
return &b
}
func BenchmarkAlloc(b *testing.B) {
for i := 0; i < b.N; i++ {
obj := make([]byte, 1024)
_ = obj
}
}

func BenchmarkPool(b *testing.B) {
for i := 0; i < b.N; i++ {
obj := bytePool.Get().(*[]byte)
_ = obj
bytePool.Put(obj)
}
}
```

文件目录下执行 `go test -bench . `

```
E:\MyGo\sync>go test -bench .
testing: warning: no tests to run
PASS
BenchmarkAlloc-4 50000000 39.3 ns/op
BenchmarkPool-4 50000000 25.4 ns/op
ok _/E_/MyGo/sync 3.345s
```

通过性能测试可以清楚地看到,使用连接池消耗的CPU时间远远小于每次手动分配内存。
```golang
func poolCleanup() {
for i, p := range allPools {
Expand Down

0 comments on commit bbfb859

Please sign in to comment.