How to Use sync.Pool to Reduce GC Pressure

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)