sync.Pool for better performance
suggest changeAllocating and freeing objects with high frequency can be relatively expensive.
A common technique for improving performance is reusing memory.
sync.Pool is a cache for reusing allocations. It is safe for concurrent use by multiple goroutines. A pool may drop every item at garbage-collection time, so a later Get can return a new value.
package main
import (
"bytes"
"fmt"
"sync"
)
var pool = sync.Pool{
// New creates an object when the pool has nothing available to return.
// New must return any. You have to type-assert
// your type after getting it.
New: func() interface{} {
// Pools often contain things like *bytes.Buffer, which are
// temporary and reusable.
return &bytes.Buffer{}
},
}
func main() {
// When getting from a Pool, you need a type assertion
s := pool.Get().(*bytes.Buffer)
// We write to the object
s.Write([]byte("dirty"))
// Then put it back
pool.Put(s)
// Pools can return a value that still holds old data.
// They can also discard it, so this Get is not guaranteed to
// return the buffer we just Put.
// Get 'another' buffer
s = pool.Get().(*bytes.Buffer)
// Write to it
s.Write([]byte("append"))
// If this is the buffer from above, it contains "dirtyappend".
// If the pool discarded it, this is a new buffer and contains "append".
fmt.Println(s)
// So use pools wisely, and clean up after yourself
s.Reset()
pool.Put(s)
// When you clean up, your buffer should be empty
s = pool.Get().(*bytes.Buffer)
// Defer your Puts to make sure you don't leak!
defer pool.Put(s)
s.Write([]byte("reset!"))
// This prints "reset!", and not "dirtyappendreset!"
fmt.Println(s)
}
dirtyappend
reset!
As with all performance optimization techniques you should not over-use sync.Pool.
Found a mistake? Have a question or improvement idea?
Let me know.
Table Of Contents