type buffer []byte // pp是用於存儲printer狀態的一個結構體 type pp struct { buf buffer arg interface{} value reflect.Value fmt fmt reordered bool goodArgNum bool panicking bool erroring bool } //一個pp的對象池 var ppFree = sync.Pool{ New: func() interface{} { return new(pp) }, } // 分配一個新的pp或者拿一個緩存的。 func newPrinter() *pp { p := ppFree.Get().(*pp) p.panicking = false p.erroring = false p.fmt.init(&p.buf) return p }
sync.Pool有兩個公開的方法。一個是Get,另外一個是Put。前者的功能是從池中獲取一個interface{}類型的值,然後者的做用則是把一個interface{}類型的值放置於池中。golang
// 一個[]byte的對象池,每一個對象爲一個[]byte var bytePool = sync.Pool{ New: func() interface{} { b := make([]byte, 1024) return &b }, } func main() { a := time.Now().Unix() // 不使用對象池 for i := 0; i < 1000000000; i++{ obj := make([]byte,1024) _ = obj } b := time.Now().Unix() // 使用對象池 for i := 0; i < 1000000000; i++{ obj := bytePool.Get().(*[]byte) _ = obj bytePool.Put(obj) } c := time.Now().Unix() fmt.Println("without pool ", b - a, "s") fmt.Println("with pool ", c - b, "s") } // without pool 34 s // with pool 24 s
上面代碼的運行結果顯示使用對象池很明顯提高了性能 緩存