Find CPU and Heap Hotspots in Go With pprof
Capture CPU and heap profiles from a Go test or net/http/pprof endpoint, read flat vs cum in go tool pprof -top, and verify that a fix actually reduced allocations. After this, you optimize measured bottlenecks instead of guessing.
Guessing which function is slow in Go usually wastes an afternoon optimizing the wrong loop. One string concatenation or unintended slice copy can account for 90% of your heap allocations while the rest of your code sits idle.
Go ships with pprof built right into go test and net/http/pprof. You can capture a CPU or memory profile in one command, inspect the top hotspots in the terminal, and verify with a benchmark that your fix actually moved the needle.
Skip ahead
Already have a .out profile file? Jump to reading flat vs. cum in go tool pprof or enabling live HTTP profiling.
1. Capture a memory profile from a benchmark
Here is a realistic example comparing naive string concatenation (buildSlow) against a pre-sized strings.Builder (buildFast):
package prof
import (
"fmt"
"strings"
"testing"
)
func buildSlow(n int) string {
s := ""
for i := range n {
s += fmt.Sprintf("item-%d,", i)
}
return s
}
func buildFast(n int) string {
var b strings.Builder
b.Grow(n * 10)
for i := range n {
b.WriteString("item-")
b.WriteString(fmt.Sprint(i))
b.WriteByte(',')
}
return b.String()
}
func BenchmarkBuildSlow(b *testing.B) {
for b.Loop() {
_ = buildSlow(200)
}
}
func BenchmarkBuildFast(b *testing.B) {
for b.Loop() {
_ = buildFast(200)
}
}
First, record a memory profile of the slow version:
$ go test -bench=BenchmarkBuildSlow -memprofile=mem.out -benchtime=200ms
goos: linux
goarch: amd64
pkg: example.com/prof
cpu: QEMU Virtual CPU version 2.5+
BenchmarkBuildSlow-2 9822 24902 ns/op
PASS
ok example.com/prof 0.249s
2. Read flat vs. cum in go tool pprof
Run go tool pprof -top on mem.out to see which functions allocated the most memory:
$ go tool pprof -top -nodecount=5 mem.out
File: prof.test
Build ID: a50a9f26f8f72ed5b821cabccd57a5025f835fcc
Type: alloc_space
Time: 2026-11-27 13:31:14 UTC
Showing nodes accounting for 1683.38MB, 100% of 1683.88MB total
Dropped 7 nodes (cum <= 8.42MB)
flat flat% sum% cum cum%
1660.38MB 98.60% 98.60% 1683.38MB 100% example.com/prof.buildSlow (inline)
23MB 1.37% 100% 23MB 1.37% fmt.Sprintf
0 0% 100% 1683.38MB 100% example.com/prof.BenchmarkBuildSlow
0 0% 100% 1683.38MB 100% testing.(*B).run1.func1
0 0% 100% 1683.38MB 100% testing.(*B).runN
flat: Allocations made directly inside that function itself (buildSlowallocated 1660.38 MB just copying growing strings with+=).cum: Cumulative allocations made by that function plus everything it calls (buildSlow+fmt.Sprintf= 1683.38 MB).
Now run both benchmarks side by side with -benchmem to verify the fix:
$ go test -bench=. -benchmem -benchtime=200ms
BenchmarkBuildSlow-2 5755 67214 ns/op 176536 B/op 399 allocs/op
BenchmarkBuildFast-2 21714 10256 ns/op 2549 B/op 191 allocs/op
Memory per call dropped from 176,536 B/op to 2,549 B/op (~69x less heap churn) and runtime dropped by 6.5x.
Which profile flag should you use?
| Profile / Flag | What it measures | When to reach for it |
|---|---|---|
-cpuprofile=cpu.out |
Where goroutines spend CPU time | High CPU usage or slow pure computation |
-memprofile=mem.out (default alloc_space) |
Total bytes allocated over the run | High GC pressure or too many allocs/op |
go tool pprof -inuse_space mem.out |
Heap memory still live at sample time | Memory usage climbing steadily (leaks) |
net/http/pprof on localhost |
Live CPU, heap, and goroutine dumps | Debugging a staging or production service |
💡 Tip
You can inspect line-by-line hotspots right in your terminal with go tool pprof -list=buildSlow mem.out, or launch a visual flame graph in your browser with go tool pprof -http=:8081 mem.out.
Common mistakes
- Exposing
net/http/pprofon the public router: Blank-importing_ "net/http/pprof"registers handlers onhttp.DefaultServeMux. Bind pprof to a separate127.0.0.1:6060listener—never your public internet port. - Confusing
alloc_spacewithinuse_space: A function with highalloc_spacecreates GC work, even if none of it leaks. Check-inuse_spacewhen RSS keeps growing. - Profiling a 10 ms run: Short runs collect too few CPU samples. Pass
-benchtime=2sor sample a live server for 30 seconds (?seconds=30).
⚠ Warning
Never assume a function is innocent because flat is 0%. Functions that delegate to JSON encoders, regexes, or database drivers show up under cum%—always sort by -cum as well as -flat.
What happens if you skip this
Without profiling, teams spend days micro-optimizing functions that account for 1% of CPU time while ignoring a single unbuffered logger or string-concatenation loop responsible for 90% of garbage collection pauses.
Related course: Go Advanced.
About
Capture CPU and heap profiles from a Go test or net/http/pprof endpoint, read flat vs cum in go tool pprof -top, and verify that a fix actually reduced allocations. After this, you optimize measured bottlenecks instead of guessing.
- Responsible
- Jay P
- Last Update
- 11/27/2026
- Reading Time
- 4 min
Reviews
Sign in to write a reviewComments
Sign in to commentNo comments yet.