Learn how to analyze and improve the efficiency of your Go code.
Optimizing performance helps reduce resource consumption, improve execution speed, and ensure better scalability.
Go provides the `pprof` tool to analyze a program's performance.
package main
import (
"fmt"
"os"
"runtime/pprof"
)
func compute() {
for i := 0; i < 1000000; i++ {
_ = i * i
}
}
func main() {
f, _ := os.Create("cpu.prof")
pprof.StartCPUProfile(f)
defer pprof.StopCPUProfile()
compute()
fmt.Println("Profiling complete")
}
Use `sync.Pool` to reduce excessive memory allocations.
package main
import (
"fmt"
"sync"
)
var bufferPool = sync.Pool{
New: func() interface{} { return make([]byte, 1024) },
}
func main() {
buffer := bufferPool.Get().([]byte)
fmt.Println("Optimized memory reuse")
bufferPool.Put(buffer)
}
performance.go
.package main
import (
"fmt"
"os"
"runtime/pprof"
"sync"
)
var bufferPool = sync.Pool{
New: func() interface{} { return make([]byte, 1024) },
}
func compute() {
for i := 0; i < 5000000; i++ {
_ = i * i
}
}
func main() {
f, _ := os.Create("cpu.prof")
pprof.StartCPUProfile(f)
defer pprof.StopCPUProfile()
compute()
fmt.Println("Profiling complete")
buffer := bufferPool.Get().([]byte)
fmt.Println("Optimizing memory usage...")
bufferPool.Put(buffer)
}
📚 Learn more about performance optimization in Go:
Read the official documentation ← Previous Exercise🚀 Enjoying these exercises? If you find them useful and want to support my work, buying me a coffee would be greatly appreciated! ☕😊