Lesson 43 of 60 · Go
Performance Tuning – CPU, Memory, and GC
Duration: 20 minutes
Tuning Tips
This lesson explains the main concept clearly with beginner-friendly examples and background so you can learn why the code works.
- Avoid allocations: reuse buffers (
bytes.Buffer), use slices from pre‑allocated pools. - Set
GOGCto control garbage‑collector aggressiveness (export GOGC=100is the default). - Use
pprofto locate hot paths. - Avoid interface{} when concrete types are known – eliminates dynamic dispatch.
Example: Buffer pool
var bufPool = sync.Pool{ New: func() any { return new(bytes.Buffer) } }
func Encode(v any) []byte {
b := bufPool.Get().(*bytes.Buffer)
b.Reset()
json.NewEncoder(b).Encode(v)
out := b.Bytes()
bufPool.Put(b)
return out
}