Reduce GC pressure by caching reusable objects in a sync.Pool and retrieving them with Get() instead of allocating new instances.
Use sync.Pool to cache frequently allocated objects, retrieving them with Get() and returning them with Put() to reduce garbage collection pressure. This pattern reuses objects instead of creating new ones, keeping the heap cleaner.
var myPool = &sync.Pool{
New: func() interface{} {
return &MyStruct{}
},
}
// Retrieve
obj := myPool.Get().(*MyStruct)
// Use obj...
// Return
myPool.Put(obj)
sync.Pool is a shared bucket of reusable objects that your program can borrow and return. It helps your application run faster and use less memory by avoiding the constant creation and destruction of temporary items. Think of it like a library of tools: instead of buying a new hammer for every nail, you borrow one, use it, and put it back for the next person.