Use sync.Pool to cache and reuse objects by calling Get() to retrieve and Put() to return them, reducing allocation overhead.
Use sync.Pool to store reusable objects that can be retrieved and reset to avoid frequent allocation and garbage collection. Create a sync.Pool variable with a New function that returns a fresh instance, then use Get() to retrieve an object and Put() to return it after use.
var pool = &sync.Pool{
New: func() interface{} {
return &MyStruct{}
},
}
obj := pool.Get().(*MyStruct)
// use obj
pool.Put(obj)
sync.Pool is a way to keep a stash of objects you've already made so you don't have to create new ones every time you need one. Think of it like a library of reusable tools: you borrow one when you need it, use it, and put it back on the shelf for the next person. This saves your computer time and memory by reusing existing items instead of constantly building new ones.