Performance Optimization
Start with Performance Optimization
In this lesson, explore performance optimization through one small Go program, and connect its output to the language rules behind it.
What you’ll learn
- Explain the main purpose of performance optimization.
- Read and run the complete Go example in this lesson.
- Apply the concept and recognize common mistakes.
Understand the idea
Optimize against a measured goal: response time, allocations, throughput or CPU usage. Start with a baseline and use benchmarks and profiles to locate expensive work.
The example preallocates a slice when its size is known. It shows a useful pattern, not a claim of universal speedup. Prefer clear correct code unless measurements justify extra complexity.
Visualize how it works
Follow this diagram before executing the example. Check where a value or decision changes what runs next.
Run a complete Go example
This example is a complete program. Save it as main.go or paste it into the Go Playground.
Go code
package main
import "fmt"
func squares(n int) []int {
result := make([]int, 0, n)
for i := 1; i <= n; i++ {
result = append(result, i*i)
}
return result
}
func main() { fmt.Println(squares(5)) }
Output
[1 4 9 16 25]Trace what the program does
Capacity is reserved up front, then values are appended. The final slice is [1 4 9 16 25]. Compare allocations in a benchmark before deciding this optimization matters.
Avoid common mistakes
- Do not assume microbenchmarks predict application-level behavior.
- Memory preallocation trades estimated capacity for fewer growth allocations.
Try it yourself
Compare squares with a version that starts with a nil slice using go test -benchmem.
Tip: Edit the example above, predict the output, and run the modified code to test your reasoning.
Check your understanding
What you should remember
You have practiced Performance Optimization in a small, self-contained program. The important habit is to predict what runs, inspect the actual output and distinguish the language rule from the particular example.
Before continuing, make sure you can explain the program to someone who has not seen it, including the line that changes its result.
Reaching the recap and completing the quizzes are separate milestones.