System Design

G21

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.

Not startedSaved in this browser only.
  1. 1Measure, profile, fix one thing, measure again. The hot spot is rarely where you expect it.
  2. 2A number means nothing without its noise. Compare the same binary with itself first.
  3. 3A CPU profile shows work. It cannot show waiting. Use the tracer for a slow request with idle CPUs.
  4. 4An allocation costs twice: once to make it and once for the collector to find it. Keep values on the stack.
G21
    A

    The trap

    recorded: same function, two benchmarks
    two benchmarks of one functiongo
    // 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++
      }
    }
    1. 1mix inlines, it has no side effects, and nothing reads the result. The compiler removes the call.
    2. 2The compiler keeps the arguments and results of calls in this loop alive.
    benchmarktime per callstatus
    for i := 0; i < b.N; i++0.3 nsMeasures an empty loop
    for b.Loop()2.2 nsMeasures 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.

    B

    The model: stack, heap and what each tool sees

    runtime defaults checked against the Go 1.27 source
    Stack of one goroutinefreed by moving one register at returnframe: Summarizescratch[128]byte, staysppointer, kept laterframe: idRouter.Routedst points into scratchHeap, shared by all goroutinesallocator, then the collectorRowmoved to heapgarbagegarbagegarbageEach object costs an allocation and a later scan.Rule: a value stays on the stack if the compiler can prove no pointer to itoutlives the frame. Inlining widens what the compiler can see.
    toolhow it seesmisses
    CPU profileStack samples at 100 Hz, on CPU onlyTime spent waiting
    Heap profileOne sample per 512 KiB allocated, by defaultStack allocations, which cost nothing
    Block, mutexOff until you set a rateWhich request waited
    Execution traceEvery scheduler event, in time orderHot 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.

    C

    The rules

    what to do and what to avoid
    rulewhystatus
    Use for b.Loop() in a new benchmarkSetup runs once, and the compiler keeps the work alive.Approved
    Call b.ReportAllocs or use -benchmemAllocations are stable when time is not. They show a change that time hides.Approved
    Run old and new in turns: A, B, A, BA change in load then falls on both sides.Approved
    Run each side at least 10 timesThe benchstat documentation asks for 10. With 3 runs, p cannot go below 0.1.Approved
    Compare a binary with itself firstThat gap is your noise floor.Approved
    Profile the real workload before you change codeThe worked example below shows why.Approved
    Use sync.Pool on a hot path that a profile namedIt adds code and a class of bugs.After a profile shows the need
    Quote a single ns/op from a laptopThe same binary moved 5% here.Not approved
    Change two things between runsYou cannot tell which one did the work.Not approved
    Benchmark a pure function with an unused result in a b.N loopSee panel A.Not approved
    Rewrite a slow path by guessingPanel 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.

    D

    Which tool for which question

    go.dev/doc/diagnostics, and tested below
    the questiontoolhow to get it
    Which function burns CPU?cpugo test -cpuprofile, /debug/pprof/profile
    What allocates the most?heap, -sample_index=alloc_spacego test -memprofile, /debug/pprof/allocs
    What holds memory now?heap, -sample_index=inuse_space/debug/pprof/heap
    Where do goroutines block?blockruntime.SetBlockProfileRate, then /debug/pprof/block
    Which lock is contended?mutexruntime.SetMutexProfileFraction, then /debug/pprof/mutex
    Is a goroutine stuck for good?goroutineleak/debug/pprof/goroutineleak, Go 1.27
    Why was this one request slow?traceruntime/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.

    E

    A benchmark that measures a service

    tested
    one sub-benchmark per stagego
    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
        })
      }
    }
    1. 1Seeded input, built once. b.Loop resets the timer on its first call.
    2. 2Adds B/op and allocs/op to the output.
    3. 3Go 1.24. This function runs once per measurement.
    4. 4A custom column. CPU time ignores the time other jobs hold the core, so it suits a busy machine.
    the commandsshell
    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.out

    My benchmark goes through the handler, because a user waits for the whole request, not for one function.

    F

    Read a comparison honestly

    recorded on a busy machine, 12 interleaved rounds
    median ± spread, then the changeoutput
    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)
    columnread 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.

    G

    The worked example: find the hot spot

    tested: every version returns the same rows
    a log summary service, first versiongo
    // 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
    }
    1. 1Compiles a pattern once per log line. Nothing about the call looks expensive.
    2. 2The regexp you suspect first. It compiles once, so the helper above is a new cost on top of this one.
    3. 3A new string per line, only to use as a map key.
    pprof -top -cumflatcum
    perf.SummarizeV00.0%85.7%
    runtime.mallocgc0.0%71.4%
    perf.routeV00.0%52.4%
    runtime.mProf_Malloc0.0%52.4%
    runtime.profilealloc0.0%52.4%
    internal/runtime/atomic.(*UnsafePointer).Load (inline)42.9%42.9%
    runtime.growslice0.0%42.9%
    runtime.stkbucket0.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.

    H

    See it: one fix per profile

    recorded: pick a stage and a profile
    stageprofile
    stageCPU per requestbytesallocations
    v07.17 ms3.8 MiB52,515
    v13.83 ms961 KiB18,494
    v2578 µs418 KiB3,769
    v3451 µs336 KiB235
    v4407 µs129 KiB219
    pprof -top -cum, CPUflatcum
    perf.SummarizeV00.0%85.7%
    runtime.mallocgc0.0%71.4%
    perf.routeV00.0%52.4%
    runtime.mProf_Malloc0.0%52.4%
    runtime.profilealloc0.0%52.4%
    internal/runtime/atomic.(*UnsafePointer).Load (inline)42.9%42.9%
    runtime.growslice0.0%42.9%
    runtime.stkbucket0.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.

    I

    Fixes 1 and 2: CPU

    tested
    v1: compile oncego
    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}")
    }
    1. 1CPU per request: 7.2 ms to 3.8 ms.
    v2: no regexpgo
    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()
    }
    1. 1A struct key has no Sprintf, and a typed compare.
    2. 2Substrings of the line: no copy and no allocation.
    3. 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.

    J

    Fixes 3 and 4: allocations

    tested
    v3: one buffer, known routesgo
    // 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
    }
    1. 1The append form lets the caller own the buffer.
    2. 2Stays on the stack. Route returns a slice of it.
    3. 3No allocation: the compiler skips the copy for a lookup.
    4. 4Without it, the row keeps the whole request body alive through a substring.
    v4: read the body oncego
    // 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
    }
    1. 1The buffer doubles, so the bytes are copied several times.
    2. 2One more full copy.
    3. 3One allocation of the right size.
    4. 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.

    K

    PGO on the same example

    measured: same code, with and without its own profile
    buildchange, median of 40 pairsfaster insign test preading
    v4 with its own profile-4.7%34 of 40under 0.001Significant
    v0 with its own profile-2.0%30 of 400.002Significant
    • 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%.
    compiler decisions that exist only with the profile-gcflags=-m
    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.ParseInt
    the production flowshell
    curl -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.

    L

    The tracer: a slow request with an idle CPU

    recorded: a cache whose refresh holds the lock
    measurerecorded
    Requests18,247
    Median request0.11 µs
    Worst request52 ms
    Requests over 20 ms24
    CPU profile, time in Cache.Getno samples
    Trace, wait in Cache.Get0.21 s in sync.Mutex.Lock
    read the snapshotshell
    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.

    M

    The flight recorder

    tested, Go 1.25
    a snapshot on the first slow requestgo
    // 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
    }
    1. 1A ring of recent trace data in memory. Nothing reaches disk until you ask.
    2. 2A hint, and it takes precedence over MinAge. Size it for your event rate.
    3. 3Only one snapshot per incident. Without this, a burst of slow requests writes a burst of files.
    4. 4Copies the window, so it holds the time before this call. A trigger after the fact still catches the cause.
    measurerecorded
    Snapshot size77 KiB
    Summary, recorder off355 µs
    Summary, recorder on355 µ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.

    N

    Escape analysis, from -gcflags=-m

    recorded: compiler output and allocations from a real run
    casethe compiler saysallocations
    return pointer, no inlinemoved to heap: p1
    return pointer, inlinednothing: no allocation to report0
    pass pointer down, read onlynothing: no allocation to report0
    pass pointer down, storedmoved to heap: p1
    box a value below 256n & 7 escapes to heap0
    box a large valuen | 1048576 escapes to heap1
    pass an int to fmtn escapes to heap2
    make, constant 1 KiBmake([]byte, 1024) does not escape0
    make, constant 128 KiBmake([]byte, 131072) escapes to heap1
    make, variable n = 32make([]byte, n) does not escape0
    make, variable n = 33make([]byte, n) does not escape1
    closure that outlives the callfunc literal escapes to heap; moved to heap: n2
    closure that dies in the callnothing: no allocation to report0
    • 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.

    O

    Allocation control

    measured, median of 5 interleaved rounds
    taskbeforeaftertimebytesallocations
    Slice of 1,000 intsappend from nilmake with capacity4,593 ns to 1,907 ns25 KiB to 8 KiB12 to 1
    Map of 1,000 intsmap literalmake with a size hint65,885 ns to 16,505 ns73 KiB to 36 KiB22 to 6
    Join 200 stringss += partBuilder with Grow40,674 ns to 1,363 ns170 KiB to 2 KiB200 to 1
    Format a recordfmt.Sprintfstrconv.AppendInt into a reused buffer135 ns to 15 ns40 B to 0 B3 to 0
    1,000 records[]*Rec[]Rec20,358 ns to 5,078 ns31 KiB to 24 KiB1,001 to 1
    Encode 200 rows and write themnew buffersync.Pool23,223 ns to 11,011 ns19 KiB to 49 B4 to 2
    Encode 200 rows and return a copynew buffersync.Pool, then bytes.Clone23,185 ns to 23,886 ns19 KiB to 21 KiB4 to 3
    Pool a 4 KiB sliceslice value in the poolpointer in the pool37 ns to 14 ns24 B to 0 B1 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.

    P

    strings and []byte

    recorded: allocations counted by a test
    expression, 41 bytesallocswhy
    s := string(b)1A string is immutable, so the conversion must copy.
    b := []byte(s)1The bytes can change, so the conversion must copy.
    m[string(b)] lookup0The compiler skips the copy for a map lookup.
    string(b) == s0A comparison keeps no reference, so no copy.
    for range []byte(s)0The loop cannot change the bytes, so no copy.
    append(buf[:0], s...)0Append copies into memory that you own.
    strings.Builder.String()0The Builder hands over its buffer with no copy.
    bytes.Buffer.String()1The Buffer stays writable, so String copies.
    s[4:10]0A substring shares the memory of s.
    strings.Clone(s[4:10])1Clone copies, so the result no longer holds s.
    keep 8 bytes of each of 100 strings of 1 MiBlive 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.

    Q

    sync.Pool

    tested
    a pooled buffer for one replygo
    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
    }
    1. 1Get returns the old contents. See the drill.
    2. 2One huge reply would otherwise stay in the pool and serve small requests.
    3. 3The bytes leave here, while the buffer stays yours. No reference survives the Put.
    box or no boxgo
    // 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
    }}
    1. 1A pointer fits in an interface. A slice header needs a box on every Put.
    the object isstatus
    Short-lived, hot, large or slow to buildApproved
    Copied out before the PutNo gain, see panel O
    A cache you expect to keepCollections empty it
    A connection that needs a closePool has no eviction hook

    A pool pays when the buffer stays inside the function. If I must copy out, the pool gives back nothing.

    R

    New in recent Go

    checked against each release's notes
    sincewhat changedwhat it means here
    1.20PGO preview with the -pgo flag. bytes.Clone. unsafe.String and StringData. B.Elapsed.Start of PGO. Clone a byte slice in one call.
    1.21PGO 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.22The 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.23PGO 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.24testing.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.25runtime/trace.FlightRecorder. The compiler allocates more slice backing stores on the stack. Green Tea collector as an experiment.Panels M and N.
    1.26B.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.27Size-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.
    S

    In the round

    45 minutes of build, 45 minutes of talk
    whenthe momentwhat to do or say
    buildMap or slice, mutex or RWMutex?Pick the simple one, and say what would make you change: a profile, not a feeling.
    buildA pattern or a regexp in a handler.Compile it once, at package level. Panel G shows the cost.
    buildYou build a list of known size.make with a capacity costs no extra typing.
    buildYou 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.

    T

    Drill

    each answer is the output of a real run

    0 of 12 known

    1. 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)
      }
    2. 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)
      }
    3. 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 string
    4. Predict 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)
      }
    5. 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)
      }
    6. 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)
      }
    7. 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)
      }
    8. 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)
      }
    9. 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())
      }
    10. 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)
      }
    11. 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)
      }
    12. 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))
      }
    U

    Numbers to say

    measured with testing.B
    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.