Golang & Concurrency (50 Qs)•Part 2: Concurrency, Channels & The GMP Scheduler (16 - 32)
What is `sync.Pool` and how does it reduce Garbage Collection pressure?
senior LevelCode ExampleMemory ManagementGolang
In Simple Words:
sync.Pool is a thread-safe object cache designed to reuse temporary objects between allocations instead of creating new heap objects.
- Ideal for reusing byte buffers, JSON decoders, and scratch slices.
- Pool entries can be automatically cleared by the runtime during any GC cycle without warning.
go
var bufferPool = sync.Pool{
New: func() any {
return new(bytes.Buffer)
},
}
func formatMessage(msg string) string {
buf := bufferPool.Get().(*bytes.Buffer)
buf.Reset()
defer bufferPool.Put(buf) // Returned for reuse!
buf.WriteString("LOG: ")
buf.WriteString(msg)
return buf.String()
}