Performance
A benchmark, a profile and a fix, one step at a time, on a small service. Every number here comes from a real run on a busy laptop, and the sheet says how much of it to trust.
- 1Measure, profile, fix one thing, measure again. The hot spot is rarely where you expect it.
- 2A number means nothing without its noise. Compare the same binary with itself first.
- 3A CPU profile shows work. It cannot show waiting. Use the tracer for a slow request with idle CPUs.
- 4An allocation costs twice: once to make it and once for the collector to find it. Keep values on the stack.
// mix is pure, and it inlines.
func mix(x uint64) uint64 {
x = bits.RotateLeft64(x*0x9E3779B97F4A7C15, 31) ^ (x >> 7)
x = bits.RotateLeft64(x*0xC2B2AE3D27D4EB4F, 29) ^ (x >> 9)
x = bits.RotateLeft64(x*0x165667B19E3779F9, 27) ^ (x >> 5)
return x * 0x9FB21C651E98DF25
}
// BenchmarkMixN looks correct. The result is unused, so the compiler can
// delete the work.
func BenchmarkMixN(b *testing.B) {
for i := 0; i < b.N; i++ {
mix(uint64(i))1
}
}
// BenchmarkMixLoop keeps the arguments and the result alive.
func BenchmarkMixLoop(b *testing.B) {
var x uint64
for b.Loop() {2
mix(x)
x++
}
}- 1mix inlines, it has no side effects, and nothing reads the result. The compiler removes the call.
- 2The compiler keeps the arguments and results of calls in this loop alive.
| benchmark | time per call | status |
|---|---|---|
| for i := 0; i < b.N; i++ | 0.3 ns | Measures an empty loop |
| for b.Loop() | 2.2 ns | Measures the work |
- The first result is 8 times too small. It looks like a good result, so nobody checks it.
- One clock cycle is 0.43 ns at 2.3 GHz. A result that close to one cycle for a real function is a warning.
- Since Go 1.26, B.Loop no longer blocks inlining of the code in its body, so a benchmark now runs the same code as production.
An old-style loop can measure nothing, because the compiler removes unused pure work. B.Loop keeps it alive.
| tool | how it sees | misses |
|---|---|---|
| CPU profile | Stack samples at 100 Hz, on CPU only | Time spent waiting |
| Heap profile | One sample per 512 KiB allocated, by default | Stack allocations, which cost nothing |
| Block, mutex | Off until you set a rate | Which request waited |
| Execution trace | Every scheduler event, in time order | Hot functions: use a profile first |
The CPU profiler samples 100 times a second, and the heap profiler once per 512 KiB allocated. So a profile is a sample, not a count.
| rule | why | status |
|---|---|---|
| Use for b.Loop() in a new benchmark | Setup runs once, and the compiler keeps the work alive. | Approved |
| Call b.ReportAllocs or use -benchmem | Allocations are stable when time is not. They show a change that time hides. | Approved |
| Run old and new in turns: A, B, A, B | A change in load then falls on both sides. | Approved |
| Run each side at least 10 times | The benchstat documentation asks for 10. With 3 runs, p cannot go below 0.1. | Approved |
| Compare a binary with itself first | That gap is your noise floor. | Approved |
| Profile the real workload before you change code | The worked example below shows why. | Approved |
| Use sync.Pool on a hot path that a profile named | It adds code and a class of bugs. | After a profile shows the need |
| Quote a single ns/op from a laptop | The same binary moved 5% here. | Not approved |
| Change two things between runs | You cannot tell which one did the work. | Not approved |
| Benchmark a pure function with an unused result in a b.N loop | See panel A. | Not approved |
| Rewrite a slow path by guessing | Panel G found the cost inside a small helper, not in the main parser. | Not approved |
I never quote one run. I compare at least 10 interleaved runs, and I say the p-value with the delta.
| the question | tool | how to get it |
|---|---|---|
| Which function burns CPU? | cpu | go test -cpuprofile, /debug/pprof/profile |
| What allocates the most? | heap, -sample_index=alloc_space | go test -memprofile, /debug/pprof/allocs |
| What holds memory now? | heap, -sample_index=inuse_space | /debug/pprof/heap |
| Where do goroutines block? | block | runtime.SetBlockProfileRate, then /debug/pprof/block |
| Which lock is contended? | mutex | runtime.SetMutexProfileFraction, then /debug/pprof/mutex |
| Is a goroutine stuck for good? | goroutineleak | /debug/pprof/goroutineleak, Go 1.27 |
| Why was this one request slow? | trace | runtime/trace.FlightRecorder, go tool trace |
Run one tool at a time. The diagnostics guide warns that the tools can interfere with each other.
High CPU gets a CPU profile. High memory gets a heap profile. A slow request with idle CPUs gets a trace.
func BenchmarkStage(b *testing.B) {
body := Body(benchLines, 1)1
for _, v := range versions {
b.Run(v.name, func(b *testing.B) {
h := v.wrap(v.fn)
b.ReportAllocs()2
start := cpuNow(b)
for b.Loop() {3
serveOne(h, body)
}
cpu := cpuNow(b) - start
b.ReportMetric(float64(cpu)/float64(b.N), "cpu-ns/op")4
})
}
}- 1Seeded input, built once. b.Loop resets the timer on its first call.
- 2Adds B/op and allocs/op to the output.
- 3Go 1.24. This function runs once per measurement.
- 4A custom column. CPU time ignores the time other jobs hold the core, so it suits a busy machine.
go test -run=^$ -bench=Stage -count=12 -cpu=1
go test -run=^$ -bench=Stage/v0 -cpuprofile=cpu.out
go tool pprof -top -cum perf.test cpu.outMy benchmark goes through the handler, because a user waits for the whole request, not for one function.
v4 vs v4, wall 407µs ±6% 408µs ±5% ~ (p=0.932 n=12)
v4 vs v4, CPU 407µs ±6% 408µs ±5% ~ (p=0.932 n=12)
v3 vs v4, CPU 451µs ±4% 407µs ±6% -9.70% (p=0.000 n=12)
v2 vs v4, CPU 578µs ±7% 407µs ±6% -29.63% (p=0.000 n=12)
v2 vs v4, 3 runs 618µs ±3% 420µs ±4% ~ (p=0.100 n=3)| column | read it as |
|---|---|
| ± | Largest distance from the median, in percent. |
| ~ | The test cannot tell the two sides apart. Claim nothing. |
| p= | The chance of a split this uneven if nothing changed. The cut-off is 0.05. |
- Wall time on the same binary moved by up to 5%, because other builds shared the machine. CPU time moved 5%.
- Row 3 has a median change of -9.7% and p = under 0.001. That passes the test.
- The last row is the same real gap as the row above it, with 3 runs. A 3 against 3 split cannot reach p below 0.1.
Computed with the same method as benchstat: medians and a Mann-Whitney U test, alpha 0.05, in a small lab function. On a quiet machine, use benchstat itself.
I run the same binary twice first. If that shows a gap, I cannot claim a smaller gap from a change.
// routeV0 replaces each number in a path with a placeholder.
func routeV0(path string) string {
re := regexp.MustCompile(`/\d+`)1
return re.ReplaceAllString(path, "/{id}")
}
// SummarizeV0 is the first version: it reads well and looks harmless.
func SummarizeV0(body string) ([]Row, error) {
rows := map[string]*Row{}
for _, line := range strings.Split(body, "\n") {
m := lineRE.FindStringSubmatch(line)2
if m == nil {
continue
}
status, err := strconv.Atoi(m[4])
if err != nil {
return nil, fmt.Errorf("status %q: %w", m[4], err)
}
size, err := strconv.ParseInt(m[5], 10, 64)
if err != nil {
return nil, fmt.Errorf("size %q: %w", m[5], err)
}
route := routeV0(m[3])
key := fmt.Sprintf("%s %s %d", m[2], route, status)3
r, ok := rows[key]
if !ok {
r = &Row{Method: m[2], Route: route, Status: status}
rows[key] = r
}
r.Count++
r.Bytes += size
}
out := make([]Row, 0, len(rows))
for _, r := range rows {
out = append(out, *r)
}
return sorted(out), nil
}- 1Compiles a pattern once per log line. Nothing about the call looks expensive.
- 2The regexp you suspect first. It compiles once, so the helper above is a new cost on top of this one.
- 3A new string per line, only to use as a map key.
| pprof -top -cum | flat | cum |
|---|---|---|
| perf.SummarizeV0 | 0.0% | 85.7% |
| runtime.mallocgc | 0.0% | 71.4% |
| perf.routeV0 | 0.0% | 52.4% |
| runtime.mProf_Malloc | 0.0% | 52.4% |
| runtime.profilealloc | 0.0% | 52.4% |
| internal/runtime/atomic.(*UnsafePointer).Load (inline) | 42.9% | 42.9% |
| runtime.growslice | 0.0% | 42.9% |
| runtime.stkbucket | 0.0% | 42.9% |
- Flat is time in the function itself. Cum adds the functions it calls. Read cum from the top to find the path, then flat to find the work.
- Shares are of request CPU, on 2,000 log lines per request. The listing is limited to the benchmark's stacks.
- One request costs 7.2 ms of CPU and 52,515 allocations.
The profile named a regexp compile inside a small helper. I would not have looked there first.
| stage | CPU per request | bytes | allocations |
|---|---|---|---|
| v0 | 7.17 ms | 3.8 MiB | 52,515 |
| v1 | 3.83 ms | 961 KiB | 18,494 |
| v2 | 578 µs | 418 KiB | 3,769 |
| v3 | 451 µs | 336 KiB | 235 |
| v4 | 407 µs | 129 KiB | 219 |
| pprof -top -cum, CPU | flat | cum |
|---|---|---|
| perf.SummarizeV0 | 0.0% | 85.7% |
| runtime.mallocgc | 0.0% | 71.4% |
| perf.routeV0 | 0.0% | 52.4% |
| runtime.mProf_Malloc | 0.0% | 52.4% |
| runtime.profilealloc | 0.0% | 52.4% |
| internal/runtime/atomic.(*UnsafePointer).Load (inline) | 42.9% | 42.9% |
| runtime.growslice | 0.0% | 42.9% |
| runtime.stkbucket | 0.0% | 42.9% |
v0: the first version.
regexp.compile takes 33% of request CPU and 74% of the bytes. It sits under routeV0, a helper that looks harmless. Fix: compile once.
Go 1.27.3, one P, median CPU time of 12 interleaved rounds. Shares are of the benchmark's own stacks.
Four small fixes cut CPU by 94%. Each one came from the profile of the version before it.
var idRE = regexp.MustCompile(`/\d+`)1
// routeV1 is the one-line fix: compile once, at package level.
func routeV1(path string) string {
return idRE.ReplaceAllString(path, "/{id}")
}- 1CPU per request: 7.2 ms to 3.8 ms.
type rowKey struct {1
method, route string
status int
}
// parseLine splits a line with strings.Cut: no regexp, no allocation.
func parseLine(line string) (method, path, status, size string, ok bool) {
_, rest, ok1 := strings.Cut(line, " ")2
method, rest, ok2 := strings.Cut(rest, " ")
path, rest, ok3 := strings.Cut(rest, " ")
status, size, ok4 := strings.Cut(rest, " ")
return method, path, status, size, ok1 && ok2 && ok3 && ok4
}
// routeV2 replaces numbers by hand. It still builds a new string per line.
func routeV2(path string) string {
var b strings.Builder3
for i := 0; i < len(path); {
if path[i] == '/' && i+1 < len(path) && isDigit(path[i+1]) {
b.WriteString("/{id}")
for i++; i < len(path) && isDigit(path[i]); i++ {
}
continue
}
b.WriteByte(path[i])
i++
}
return b.String()
}- 1A struct key has no Sprintf, and a typed compare.
- 2Substrings of the line: no copy and no allocation.
- 3Still one new string per line. The heap profile shows it next.
First I removed the waste with one line. Then I removed the regexp, because this format does not need one.
// Router writes the normalized form of path into dst. An interface keeps
// the rule replaceable; PGO measures what that costs below.
type Router interface {
Route(dst []byte, path string) []byte1
}
type idRouter struct{}
func (idRouter) Route(dst []byte, path string) []byte {
for i := 0; i < len(path); {
if path[i] == '/' && i+1 < len(path) && isDigit(path[i+1]) {
dst = append(dst, "/{id}"...)
for i++; i < len(path) && isDigit(path[i]); i++ {
}
continue
}
dst = append(dst, path[i])
i++
}
return dst
}
// Summarizer3 reuses one route buffer and one table of known routes.
type Summarizer3 struct {
Router Router
}
// Summarize allocates per distinct row, not per line.
func (s Summarizer3) Summarize(body string) ([]Row, error) {
routes := make(map[string]string, 16)
rows := make(map[rowKey]*Row, 64)
var scratch [128]byte2
for line := range strings.Lines(body) {
method, path, st, sz, ok := parseLine(strings.TrimSuffix(line, "\n"))
if !ok {
continue
}
status, err := strconv.Atoi(st)
if err != nil {
return nil, fmt.Errorf("status %q: %w", st, err)
}
size, err := strconv.ParseInt(sz, 10, 64)
if err != nil {
return nil, fmt.Errorf("size %q: %w", sz, err)
}
buf := s.Router.Route(scratch[:0], path)
route, ok := routes[string(buf)]3
if !ok {
route = string(buf)
routes[route] = route
}
k := rowKey{method, route, status}
r, ok := rows[k]
if !ok {
r = &Row{Method: strings.Clone(method)4, Route: route, Status: status}
rows[k] = r
}
r.Count++
r.Bytes += size
}
out := make([]Row, 0, len(rows))
for _, r := range rows {
out = append(out, *r)
}
return sorted(out), nil
}- 1The append form lets the caller own the buffer.
- 2Stays on the stack. Route returns a slice of it.
- 3No allocation: the compiler skips the copy for a lookup.
- 4Without it, the row keeps the whole request body alive through a substring.
// readAll grows a buffer by doubling, then copies it into a string.
func readAll(r *http.Request) (string, error) {
body, err := io.ReadAll(r.Body)1
if err != nil {
return "", fmt.Errorf("read body: %w", err)
}
return string(body)2, nil
}
// readSized allocates once and hands the buffer over with no second copy.
func readSized(r *http.Request) (string, error) {
var b strings.Builder
if r.ContentLength > 0 {
b.Grow(int(r.ContentLength))3
}
if _, err := io.Copy(&b, r.Body); err != nil {
return "", fmt.Errorf("read body: %w", err)
}
return b.String()4, nil
}- 1The buffer doubles, so the bytes are copied several times.
- 2One more full copy.
- 3One allocation of the right size.
- 4Builder hands over its buffer with no copy.
The heap profile found this. The code was outside the function that the sheet set out to fix.
An allocation fix may not move time on a noisy box. I still check B/op, because it lowers collector work in production.
| build | change, median of 40 pairs | faster in | sign test p | reading |
|---|---|---|---|---|
| v4 with its own profile | -4.7% | 34 of 40 | under 0.001 | Significant |
| v0 with its own profile | -2.0% | 30 of 40 | 0.002 | Significant |
- The U test on the first 12 rounds of v4 gave -4.1%, p = 0.004. Each pair runs back to back, so a slow change in load falls on both sides. Quote the paired result.
- On v0 the profile cannot remove the waste. The one-line fix in panel I saved 47%.
- The Go docs give 2 to 14% for a representative set of programs, as of Go 1.22.
- The binary grew by 52 KiB, or 0.5%.
PGO devirtualizing interface call s.Router.Route to idRouter.Route
inlining call to Summarizer3.Summarize
inlining call to idRouter.Route
inlining call to parseLine
inlining call to strconv.ParseIntcurl -o cmd/server/default.pgo \
"$HOST/debug/pprof/profile?seconds=30"
go build ./cmd/server- go build finds default.pgo in the main package with no flag.
- The docs recommend a production profile. They call microbenchmarks poor sources, so this example shows a best case.
PGO gave 5% with no code change. It does not repair slow code, so I fix the hot spot first.
| measure | recorded |
|---|---|
| Requests | 18,247 |
| Median request | 0.11 µs |
| Worst request | 52 ms |
| Requests over 20 ms | 24 |
| CPU profile, time in Cache.Get | no samples |
| Trace, wait in Cache.Get | 0.21 s in sync.Mutex.Lock |
go tool trace -pprof=sync snapshot.trace > sync.prof
go tool pprof -top -cum sync.prof
# or open the timeline in a browser
go tool trace snapshot.trace- A CPU profile samples running code. A goroutine that waits for a lock is not running, so it leaves no sample.
- The sync profile comes from the trace. It totals the time each stack spent blocked.
- The tracer shows goroutines in time order: run, wait, wake. It does not rank hot functions, so use a profile for that.
The median request took 0.1 µs and the worst took 52 ms. The CPU profile showed nothing, and the trace named the lock.
// Watch writes one trace snapshot when a request runs longer than limit.
type Watch struct {
fr *trace.FlightRecorder
limit time.Duration
once atomic.Bool
out io.Writer
}
// NewWatch starts a flight recorder that keeps at least the last 2 s.
func NewWatch(limit time.Duration, out io.Writer) (*Watch, error) {
fr := trace.NewFlightRecorder(trace.FlightRecorderConfig{1
MinAge: 2 * time.Second,
MaxBytes: 16 << 20,2
})
if err := fr.Start(); err != nil {
return nil, fmt.Errorf("start flight recorder: %w", err)
}
return &Watch{fr: fr, limit: limit, out: out}, nil
}
// Stop ends the recording.
func (w *Watch) Stop() { w.fr.Stop() }
// Observe runs after a request. The snapshot covers the slow request,
// because the recorder already holds the time before this call.
func (w *Watch) Observe(took time.Duration) error {
if took < w.limit || !w.once.CompareAndSwap(false, true)3 {
return nil
}
if _, err := w.fr.WriteTo(w.out)4; err != nil {
return fmt.Errorf("write trace snapshot: %w", err)
}
return nil
}- 1A ring of recent trace data in memory. Nothing reaches disk until you ask.
- 2A hint, and it takes precedence over MinAge. Size it for your event rate.
- 3Only one snapshot per incident. Without this, a burst of slow requests writes a burst of files.
- 4Copies the window, so it holds the time before this call. A trigger after the fact still catches the cause.
| measure | recorded |
|---|---|
| Snapshot size | 77 KiB |
| Summary, recorder off | 355 µs |
| Summary, recorder on | 355 µs |
| Change | +0.2%, p = 0.912 |
- This run found no measurable cost for the recorder on this workload.
- Only one flight recorder can run at a time in a process.
- A plain go test -trace or trace.Start writes the whole run. Use the recorder when you do not know when the event comes.
I keep the last seconds of trace in memory and write them out when a request breaks its limit, so a rare event leaves evidence.
| case | the compiler says | allocations |
|---|---|---|
| return pointer, no inline | moved to heap: p | 1 |
| return pointer, inlined | nothing: no allocation to report | 0 |
| pass pointer down, read only | nothing: no allocation to report | 0 |
| pass pointer down, stored | moved to heap: p | 1 |
| box a value below 256 | n & 7 escapes to heap | 0 |
| box a large value | n | 1048576 escapes to heap | 1 |
| pass an int to fmt | n escapes to heap | 2 |
| make, constant 1 KiB | make([]byte, 1024) does not escape | 0 |
| make, constant 128 KiB | make([]byte, 131072) escapes to heap | 1 |
| make, variable n = 32 | make([]byte, n) does not escape | 0 |
| make, variable n = 33 | make([]byte, n) does not escape | 1 |
| closure that outlives the call | func literal escapes to heap; moved to heap: n | 2 |
| closure that dies in the call | nothing: no allocation to report | 0 |
- The two variable make rows show a limit. The code gets a small stack buffer: size 32 fits and size 33 goes to the heap. The diagnostic is the same for both.
- Escapes to heap does not always mean an allocation. An interface value below 256 uses a static table.
- A compiler message describes this build. Inlining and the Go version change it, so count allocations in a test too.
I read go build -gcflags=-m. Moved to heap names the variable, and inlining can remove the allocation.
| task | before | after | time | bytes | allocations |
|---|---|---|---|---|---|
| Slice of 1,000 ints | append from nil | make with capacity | 4,593 ns to 1,907 ns | 25 KiB to 8 KiB | 12 to 1 |
| Map of 1,000 ints | map literal | make with a size hint | 65,885 ns to 16,505 ns | 73 KiB to 36 KiB | 22 to 6 |
| Join 200 strings | s += part | Builder with Grow | 40,674 ns to 1,363 ns | 170 KiB to 2 KiB | 200 to 1 |
| Format a record | fmt.Sprintf | strconv.AppendInt into a reused buffer | 135 ns to 15 ns | 40 B to 0 B | 3 to 0 |
| 1,000 records | []*Rec | []Rec | 20,358 ns to 5,078 ns | 31 KiB to 24 KiB | 1,001 to 1 |
| Encode 200 rows and write them | new buffer | sync.Pool | 23,223 ns to 11,011 ns | 19 KiB to 49 B | 4 to 2 |
| Encode 200 rows and return a copy | new buffer | sync.Pool, then bytes.Clone | 23,185 ns to 23,886 ns | 19 KiB to 21 KiB | 4 to 3 |
| Pool a 4 KiB slice | slice value in the pool | pointer in the pool | 37 ns to 14 ns | 24 B to 0 B | 1 to 0 |
A value slice also keeps the elements next to each other, so the collector has no pointers to follow in them.
I set capacity when I know the size, use a Builder for text, and keep records in a value slice.
| expression, 41 bytes | allocs | why |
|---|---|---|
| s := string(b) | 1 | A string is immutable, so the conversion must copy. |
| b := []byte(s) | 1 | The bytes can change, so the conversion must copy. |
| m[string(b)] lookup | 0 | The compiler skips the copy for a map lookup. |
| string(b) == s | 0 | A comparison keeps no reference, so no copy. |
| for range []byte(s) | 0 | The loop cannot change the bytes, so no copy. |
| append(buf[:0], s...) | 0 | Append copies into memory that you own. |
| strings.Builder.String() | 0 | The Builder hands over its buffer with no copy. |
| bytes.Buffer.String() | 1 | The Buffer stays writable, so String copies. |
| s[4:10] | 0 | A substring shares the memory of s. |
| strings.Clone(s[4:10]) | 1 | Clone copies, so the result no longer holds s. |
| keep 8 bytes of each of 100 strings of 1 MiB | live heap |
|---|---|
| s[:8] | 100 MiB |
| strings.Clone(s[:8]) | 3.5 KiB |
- A substring keeps its whole parent alive. Clone what you keep from a large buffer.
- unsafe.String avoids the copy, and any later write to the bytes changes the string. Use it only with a profile and a written reason.
- The compiler has a small temporary buffer for short conversions, so the counts above use a longer string.
A conversion copies, unless the compiler can prove that the copy is not needed. Map lookups and comparisons are the common cases.
var buffers = sync.Pool{New: func() any { return new(bytes.Buffer) }}
// maxPooled keeps one huge reply from pinning a huge buffer in the pool.
const maxPooled = 64 << 10
// RenderPooled encodes rows into a pooled buffer and writes it out, so no
// reference to the buffer leaves this function.
func RenderPooled(w io.Writer, rows []Row) error {
b := buffers.Get().(*bytes.Buffer)
b.Reset()1
defer func() {
if b.Cap() <= maxPooled {2
buffers.Put(b)
}
}()
if err := json.NewEncoder(b).Encode(rows); err != nil {
return fmt.Errorf("encode rows: %w", err)
}
if _, err := w.Write(b.Bytes())3; err != nil {
return fmt.Errorf("write rows: %w", err)
}
return nil
}- 1Get returns the old contents. See the drill.
- 2One huge reply would otherwise stay in the pool and serve small requests.
- 3The bytes leave here, while the buffer stays yours. No reference survives the Put.
// poolSlice stores a slice in the pool. The slice header boxes into an
// interface on every Put, and that allocates.
var poolSlice = sync.Pool{New: func() any { return make([]byte, 0, 4096) }}
// poolPtr stores a pointer, which fits an interface with no box.
var poolPtr = sync.Pool{New: func() any {
b := make([]byte, 0, 4096)
return &b1
}}- 1A pointer fits in an interface. A slice header needs a box on every Put.
| the object is | status |
|---|---|
| Short-lived, hot, large or slow to build | Approved |
| Copied out before the Put | No gain, see panel O |
| A cache you expect to keep | Collections empty it |
| A connection that needs a close | Pool has no eviction hook |
A pool pays when the buffer stays inside the function. If I must copy out, the pool gives back nothing.
| since | what changed | what it means here |
|---|---|---|
| 1.20 | PGO preview with the -pgo flag. bytes.Clone. unsafe.String and StringData. B.Elapsed. | Start of PGO. Clone a byte slice in one call. |
| 1.21 | PGO ready for general use, default.pgo found automatically. Tracing CPU cost up to 10 times lower on amd64 and arm64. | Panel K. Tracing in production becomes realistic. |
| 1.22 | The execution tracer is rebuilt. PGO devirtualizes more calls: 2 to 14%. Mutex profiles scale by the number of waiters. | Traces can be cut into pieces, which the flight recorder needs. |
| 1.23 | PGO build overhead falls to single-digit percent. pprof stacks grow to 128 frames for alloc, mutex and block profiles. | PGO costs little to keep on. |
| 1.24 | testing.B.Loop. strings.Lines and SplitSeq. T.Context and B.Context. | Panels A and E. v3 ranges over lines with no slice of lines. |
| 1.25 | runtime/trace.FlightRecorder. The compiler allocates more slice backing stores on the stack. Green Tea collector as an experiment. | Panels M and N. |
| 1.26 | B.Loop no longer blocks inlining in its body. Green Tea is the default: 10 to 40% less collector overhead expected. More stack-allocated slices. bytes.Buffer.Peek. pprof -http opens the flame graph. | Allocations cost less to collect. Benchmarks run the real code. |
| 1.27 | Size-specialized allocation: small allocations cost up to 30% less, about 1% overall. goroutineleak profile. strings.CutLast and bytes.CutLast. Tracebacks show pprof labels. | Panel D. Allocation-heavy code improves with no change. |
| when | the moment | what to do or say |
|---|---|---|
| build | Map or slice, mutex or RWMutex? | Pick the simple one, and say what would make you change: a profile, not a feeling. |
| build | A pattern or a regexp in a handler. | Compile it once, at package level. Panel G shows the cost. |
| build | You build a list of known size. | make with a capacity costs no extra typing. |
| build | You feel the urge to pool or to avoid allocations. | Do not. Say that the service has no measured problem yet. |
| talk | "It got slow in production. What do you do?" | Read the metrics, take a CPU profile from /debug/pprof, then read cum from the top. |
| talk | "p99 is high, and CPU is idle." | The time is in waits. Use the mutex and block profiles, and a flight recorder keyed on slow requests. |
| talk | "Memory keeps growing." | Compare two heap profiles of inuse_space. Check the goroutine count, then look for substrings that pin large buffers. |
| talk | "The collector takes 25% of CPU." | Lower allocations from the alloc_space profile, then consider GOMEMLIMIT and GOGC. |
| talk | "How do you know the fix worked?" | Interleaved runs, the same binary as a control, a p-value. Then a canary under real load. |
In the build I write clear code and say where I would measure. In the talk I bring the profile, not a guess.
0 of 12 known
Predict the output. The first value compares the two counts.
package main import ( "fmt" "testing" ) var out []int func main() { grow := testing.AllocsPerRun(100, func() { var s []int for i := range 1000 { s = append(s, i) } out = s }) sized := testing.AllocsPerRun(100, func() { s := make([]int, 0, 1000) for i := range 1000 { s = append(s, i) } out = s }) fmt.Println(sized < grow, sized) }Predict the output.
package main import ( "fmt" "testing" ) var sink any func main() { n := 7 small := testing.AllocsPerRun(100, func() { sink = n }) n = 7000 large := testing.AllocsPerRun(100, func() { sink = n }) fmt.Println(small, large) }Predict the output.
package main import ( "fmt" "testing" ) var count int func main() { b := []byte("a key of forty bytes, long enough to copy") m := map[string]int{string(b): 1} lookup := testing.AllocsPerRun(100, func() { count = m[string(b)] }) keep := testing.AllocsPerRun(100, func() { k := string(b) count = m[k] + len(k) sink = k }) fmt.Println(lookup, keep) } var sink stringPredict the output.
package main import ( "fmt" "testing" ) type point struct{ x, y int } func near() *point { return &point{1, 2} } //go:noinline func far() *point { return &point{1, 2} } var n int func main() { a := testing.AllocsPerRun(100, func() { n = near().x }) b := testing.AllocsPerRun(100, func() { n = far().x }) fmt.Println(a, b) }Predict the output.
package main import ( "fmt" "testing" ) var f func() int func main() { local := testing.AllocsPerRun(100, func() { n := 0 add := func() { n++ } add() }) kept := testing.AllocsPerRun(100, func() { n := 0 f = func() int { n++; return n } }) fmt.Println(local, kept) }Predict the output.
package main import ( "fmt" "strconv" "testing" ) var ( sink string n = 123456 ) func main() { viaFmt := testing.AllocsPerRun(100, func() { sink = fmt.Sprint(n) }) viaConv := testing.AllocsPerRun(100, func() { sink = strconv.Itoa(n) }) fmt.Println(viaFmt, viaConv) }Predict the output. The first value compares the two counts.
package main import ( "fmt" "strings" "testing" ) var sink string func build(grow bool) { var b strings.Builder if grow { b.Grow(1024) } for range 1024 { b.WriteByte('x') } sink = b.String() } func main() { plain := testing.AllocsPerRun(100, func() { build(false) }) sized := testing.AllocsPerRun(100, func() { build(true) }) fmt.Println(plain > 1, sized) }Predict the output.
package main import ( "fmt" "testing" "time" ) func main() { loopSetups, nSetups := 0, 0 testing.Benchmark(func(b *testing.B) { loopSetups++ time.Sleep(time.Millisecond) for b.Loop() { time.Sleep(time.Millisecond) } }) testing.Benchmark(func(b *testing.B) { nSetups++ time.Sleep(time.Millisecond) b.ResetTimer() for range b.N { time.Sleep(time.Millisecond) } }) fmt.Println(loopSetups, nSetups > 1) }Predict the output. The program uses one P, so a Get sees the Put.
package main import ( "fmt" "runtime" "sync" ) func main() { runtime.GOMAXPROCS(1) p := sync.Pool{New: func() any { return "new" }} p.Put("old") runtime.GC() fmt.Println(p.Get()) p.Put("old") runtime.GC() runtime.GC() fmt.Println(p.Get()) }Predict the output.
package main import ( "bytes" "fmt" "runtime" "sync" ) func main() { runtime.GOMAXPROCS(1) p := sync.Pool{New: func() any { return new(bytes.Buffer) }} b := p.Get().(*bytes.Buffer) b.WriteString("secret") p.Put(b) c := p.Get().(*bytes.Buffer) c.WriteString("!") fmt.Println(c.String(), b == c) }Predict the output.
package main import ( "fmt" "sync" "testing" ) func main() { byValue := sync.Pool{New: func() any { return make([]byte, 16) }} byPointer := sync.Pool{New: func() any { b := make([]byte, 16) return &b }} value := testing.AllocsPerRun(100, func() { b := byValue.Get().([]byte) byValue.Put(b) }) pointer := testing.AllocsPerRun(100, func() { b := byPointer.Get().(*[]byte) byPointer.Put(b) }) fmt.Println(value, pointer) }Predict the output.
package main import ( "fmt" "strings" "unsafe" ) func main() { s := strings.Repeat("x", 1<<20) a := s[:8] b := strings.Clone(s[:8]) fmt.Println(unsafe.StringData(a) == unsafe.StringData(s)) fmt.Println(unsafe.StringData(b) == unsafe.StringData(s)) }
- first fix
- 7.2 ms to 3.8 ms with one line.
- all fixes
- 7.2 ms to 407 µs; 52,515 to 219 allocations.
- Sprintf
- 135 ns, against 15 ns for strconv into a buffer.
- prealloc
- A 1,000 element slice: 12 allocations become 1.
- substring
- 8 bytes can keep 1 MiB alive.
- stack make
- Up to 32 bytes for a variable size.
- profilers
- CPU at 100 Hz; heap each 512 KiB.
- PGO
- -4.7% on the final version.
Go 1.27.3, 8-core Intel i9 laptop, on a busy machine. Use these as orders of magnitude.