Mega List of Tips for Writing Performant Go Code
January 18, 2025 ยท View on GitHub
Stack vs Heap Allocations
For variable with short lived scope, use non-pointer return value. For variable with long lived scope, use pointer return value. Heap allocation is expensive.
Benchmark: https://github.com/Bhupesh-V/pocs/tree/main/go/heap-escape
Buffer Pools
Use sync.Pool for frequently allocated and released objects. Buffer pool is a good example.
Benchmark: https://github.com/Bhupesh-V/pocs/tree/main/go/buffer-pool
Working with strings
Use strings.Builder in favor of bytes.Buffer for string operations.
Capping slice length
Pre-allcate memory for slices, maps if possible (when using make()).