【Golang】使用 - sync.Pool

Posted by 西维蜀黍 on 2021-07-19, Last Modified on 2021-09-21

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