Junior — Middle
Can you explain the working principle and usage of the sync.Pool object in Go?
sobes.tech AI
Answer from AI
sync.Pool in Go is a structure for storing and reusing temporary objects to reduce the load on the garbage collector and improve performance.
Working principle:
sync.Poolcontains a pool of objects of the same type.- When calling
Get(), the pool returns an object from the internal storage if available, or creates a new one using theNewfunction if defined. - After use, the object is returned to the pool via
Put().
Usage:
- Suitable for objects with a short lifecycle, such as buffers or temporary structures.
- Helps avoid frequent memory allocation and deallocation.
Example:
var bufPool = sync.Pool{
New: func() interface{} {
return make([]byte, 1024) // 1KB buffer
},
}
func process() {
buf := bufPool.Get().([]byte) // get buffer
defer bufPool.Put(buf) // return buffer to pool
// use buf for operations
}
Important: objects in the pool can be cleared by the garbage collector, so you cannot rely on the object always being preserved.