Exercise 6: Performance Optimization in Go

Learn how to analyze and improve the efficiency of your Go code.

Why Optimize Performance?

Optimizing performance helps reduce resource consumption, improve execution speed, and ensure better scalability.

Performance Analysis with `pprof`

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")
}

Optimizing Memory Usage

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)
}

Exercise Instructions

  • Create a file named performance.go.
  • Add a CPU-intensive function.
  • Analyze performance using `pprof`.
  • Optimize memory usage with `sync.Pool`.

Exercise Solution

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)
}

Best Practices and Common Errors

  • ✅ Always profile a program before optimizing.
  • ✅ Use `sync.Pool` to manage memory efficiently.
  • ✅ Identify CPU-intensive functions before modifying them.
  • ⚠️ Avoid excessive memory allocations.

📚 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! ☕😊


☕ Buy me a coffee