From bbfb859aa8951abb92acc93fb239d44a18270ad0 Mon Sep 17 00:00:00 2001 From: lintanghui Date: Fri, 25 Mar 2016 16:13:14 +0800 Subject: [PATCH] =?UTF-8?q?=E6=B7=BB=E5=8A=A0pool=20benchmark?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- chapter16/16.01.md | 47 ++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 47 insertions(+) diff --git a/chapter16/16.01.md b/chapter16/16.01.md index 210191a..5e3d4d8 100644 --- a/chapter16/16.01.md +++ b/chapter16/16.01.md @@ -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 {