Lab 04: sync.Pool & Allocators
Overview
Step 1: sync.Pool Basics
sync.Pool Basicspackage main
import (
"bytes"
"fmt"
"sync"
)
var bufPool = sync.Pool{
New: func() interface{} {
// Called when pool is empty
buf := new(bytes.Buffer)
buf.Grow(256) // pre-allocate
return buf
},
}
func processRequest(data string) string {
buf := bufPool.Get().(*bytes.Buffer)
buf.Reset() // always reset before use
defer bufPool.Put(buf)
buf.WriteString("processed: ")
buf.WriteString(data)
return buf.String()
}
func main() {
// First call: pool is empty, New() is called
result1 := processRequest("hello")
fmt.Println(result1)
// Second call: pool reuses the buffer
result2 := processRequest("world")
fmt.Println(result2)
}Step 2: Object Pool for HTTP Responses
Step 3: Benchmark — Pool vs No-Pool
Step 4: bytes.Buffer Pooling Pattern
bytes.Buffer Pooling PatternStep 5: GC Interaction with sync.Pool
Step 6: Channel-Based Permanent Pool
Step 7: Arena Allocator Concept (Go 1.20+)
Step 8: Capstone — HTTP Server with Full Pooling
Summary
Pattern
Allocs/op
Use Case
Last updated
