pprof Bottleneck Hunt (Go)
Topics: performance, profiling, allocations, Go runtime/GC
Problem
CountLevels and BuildCSV already pass their tests — but both are needlessly slow. Optimize
them without changing behavior; the leaderboard ranks your benchmark's speed and allocations.
func CountLevels(lines []string) map[string]int // "[INFO] ..." -> {INFO: n}
func BuildCSV(rows [][]string) string // rows -> comma/newline CSV text
CountLevels compiles its regex inside the loop — a CPU hotspot. Compile it once.
BuildCSV assembles the result with += string concatenation — O(n²) copying and
allocations. Build it with a strings.Builder instead.
- Keep the outputs identical: the correctness tests must still pass.
How it's graded: the tests must pass (they already do), and your submission's benchmark — ns/op
and allocations per op — shows on the leaderboard. Lower is better; ~1.0× is the reference solution.
Key concepts
regexp.MustCompile in a hot loop: compiling a regex is expensive (parsing + building an
NFA) — doing it once per call instead of once per iteration is a classic CPU bottleneck.
- String concatenation with
+=: each += allocates a brand-new string and copies everything
so far — O(n²) total work and allocations for n appends. strings.Builder grows a buffer
geometrically, like append on a slice.
-alloc_space vs -alloc_objects: when profiling, -alloc_space shows total bytes ever
allocated (great for finding O(n²) copying); -alloc_objects shows allocation count (great for
finding per-iteration allocations the GC must collect).
Profile it locally (optional): clone the repo and run
go test -bench=. -benchmem -cpuprofile=cpu.out -memprofile=mem.out ./challenges/pprof-bottleneck/go/,
then go tool pprof -top cpu.out (CPU) or go tool pprof -top -alloc_space mem.out (allocations)
to pinpoint the hotspots before optimizing.
Sign in to submit your solution.