sync.Pool for better performance:
sync.Pool for better performance
suggest changeAllocating and freeing objects with high frequency can be relatively expensive.
A common technique for improving performance is re-using memory.
sync.Pool is a thread-safe cache for re-using allocations.
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 an interface{} to make it flexible. You have to cast
// your type after getting it.
New: func() interface{} {
// Pools often contain things like *bytes.Buffer, which are
// temporary and re-usable.
return &bytes.Buffer{}
},
}
func main() {
// When getting from a Pool, you need to cast
s := pool.Get().(*bytes.Buffer)
// We write to the object
s.Write([]byte("dirty"))
// Then put it back
pool.Put(s)
// Pools can return dirty results
// Get 'another' buffer
s = pool.Get().(*bytes.Buffer)
// Write to it
s.Write([]byte("append"))
// At this point, if GC ran, this buffer *might* exist already, in
// which case it will contain the bytes of the string "dirtyappend"
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
4
Strings
5
Pointers
6
Arrays
7
Slices
8
Maps
9
Structs
10
Interfaces
15
Functions
16
Methods
18
Defer
20
Concurrency
22
Mutex
23
Packages
27
Logging
30
JSON
31
XML
32
CSV
33
YAML
34
SQL
35
HTTP Client
36
HTTP Server
38
Reflection
39
Context
40
Package fmt
41
OS Signals
42
Testing
48
sync.Pool for better performance
49
gob
50
Plugin
53
Console I/O
54
Cryptography
59
Contributors