Why to use sync.Pool
?
We want to keep the GC overhead as little as possible. Frequent allocation and recycling of memory will cause a heavy burden to GC. sync.Pool
can cache objects that are not used temporarily and use them directly (without reallocation) when they are needed next time. This can potentially reduce the GC workload and improve the performance.
How to use sync.Pool
?
First you need to set the New
function. This function will be used when there is no cached object in the Pool. After that you only need using Get
and Put
methods to retrieve and return objects. Also a Pool must not be copied after first use.
Due to New
function type, which is func() interface{}
, Get
method returns an interface{}
. So you need to do a type assertion in order to get the concrete object.
// A dummy struct
type Person struct {
Name string
}
// Initializing pool
var personPool = sync.Pool{
// New optionally specifies a function to generate
// a value when Get would otherwise return nil.
// The Pool's New function should generally only return pointer types, since a pointer can be put into the return interface value without an allocation:
New: func() interface{} { return new(Person) },
}
// Main function
func main() {
// Get hold of an instance
newPerson := personPool.Get().(*Person)
// Defer release function
// After that the same instance is
// reusable by another routine
defer personPool.Put(newPerson)
// Using the instance
newPerson.Name = "Jack"
}
Reference
FEATURED TAGS
algorithm
algorithmproblem
architecturalpattern
architecture
aws
c#
cachesystem
codis
compile
concurrentcontrol
database
dataformat
datastructure
debug
design
designpattern
distributedsystem
django
docker
domain
engineering
freebsd
git
golang
grafana
hackintosh
hadoop
hardware
hexo
http
hugo
ios
iot
java
javaee
javascript
kafka
kubernetes
linux
linuxcommand
linuxio
lock
macos
markdown
microservices
mysql
nas
network
networkprogramming
nginx
node.js
npm
oop
openwrt
operatingsystem
padavan
performance
programming
prometheus
protobuf
python
redis
router
security
shell
software testing
spring
sql
systemdesign
truenas
ubuntu
vmware
vpn
windows
wmware
wordpress
xml
zookeeper