[{"data":1,"prerenderedAt":-1},["ShallowReactive",2],{"skill:01M7BQDVG7DH2G9Z97Y8H3P3E9":3,"skill-same:01M7BQDVG7DH2G9Z97Y8H3P3E9":74},{"skillNo":4,"name":5,"nameZh":6,"description":7,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":16,"categories":17,"keywords":18,"publishedAt":19,"linkOnly":20,"markdownContent":21,"markdownBody":22,"frontMatter":23,"refName":25,"commitSha":26,"skillDirectory":27,"forksCount":28,"repositoryHtmlUrl":29,"repositoryHomepageUrl":6,"ownerHtmlUrl":30,"ownerBlogUrl":6,"ownerDescription":6,"updatedAt":31,"install":32,"resources":45},"01M7BQDVG7DH2G9Z97Y8H3P3E9","go-performance",null,"Use when optimizing slow or performance-critical Go code, allocations, string concatenation in loops, or benchmarks. Also use when writing or reviewing a cache, including implementing one from a stub — its key, its expiry, and how a miss loads. Concurrent code patterns belong to go-concurrency.","h0rn3t\u002Fgolang-skills","h0rn3t","https:\u002F\u002Favatars.githubusercontent.com\u002Fu\u002F1213719?v=4","01M7BQBDJ8D4P5W7EQHBD464BX","Eugene Shershen","01M7BQBDJXMTCKNCEDKVEYDRGA",7,"Apache-2.0","https:\u002F\u002Fgithub.com\u002Fh0rn3t\u002Fgolang-skills\u002Fblob\u002Fmain\u002Fskills\u002Fgo-performance\u002FSKILL.md",[],[],"2026-11-15 14:19:17",false,"---\nname: go-performance\ndescription: Use when optimizing slow or performance-critical Go code, allocations, string concatenation in loops, or benchmarks. Also use when writing or reviewing a cache, including implementing one from a stub — its key, its expiry, and how a miss loads. Concurrent code patterns belong to go-concurrency.\nallowed-tools: Bash(bash ${CLAUDE_SKILL_DIR}\u002Fscripts\u002F*)\n---\n\n# Go Performance Patterns\n\n> Compatibility: Baseline Go 1.27 (see [COMPATIBILITY.md](..\u002Fgo-style-core\u002Freferences\u002FCOMPATIBILITY.md)). `b.Loop()`\n> requires Go 1.24+; `encoding\u002Fjson\u002Fv2` Go 1.27+; cgroup-aware `GOMAXPROCS`\n> Go 1.25+.\n\n## Resource Routing\n\n- `scripts\u002Fbench-compare.sh` - Run when comparing benchmark results, saving baselines, or producing JSON benchmark metadata.\n- `scripts\u002Fbench-verdict.go` - The statistics helper `bench-compare.sh --verdict` builds and calls; `scripts\u002Fbench-verdict_test.go` holds its unit tests. Neither is run or read directly.\n- `references\u002FBENCHMARKS.md` - Read when writing benchmarks, using benchstat, or profiling with pprof.\n- `references\u002FSTRING-OPTIMIZATION.md` - Read when optimizing concatenation or memory retained by substrings.\n- `references\u002FRUNTIME.md` - Read when setting `GOMAXPROCS`, `GOGC`, `GOMEMLIMIT`, or a PGO profile, or removing `automaxprocs`.\n\nApply performance-specific guidance to measured bottlenecks, including retained\nmemory. Don't add allocations or complexity without evidence that it helps.\n\n---\n\n## Prefer strconv over fmt\n\nFor direct primitive conversions, prefer `strconv` by default; choosing it\nneeds no benchmark:\n\n```go\ns := strconv.Itoa(n)\n```\n\n---\n\n## Avoid Repeated String-to-Byte Conversions\n\nFor a measured repeated-conversion cost, reuse the bytes outside the loop.\nThe compiler may already eliminate the conversion allocation for a concrete\nwriter, so compare the actual call site:\n\n```go\ndata := []byte(\"Hello world\")\nfor b.Loop() { \u002F\u002F Go 1.24+\n    w.Write(data)\n}\n```\n\n---\n\n## Prefer Specifying Container Capacity\n\nPreallocate when the final size is known at the call site (`len(files)`, a fixed loop bound); otherwise measure before guessing a capacity — an oversized estimate retains memory the workload never uses.\n\n---\n\n## Pass Values\n\nA pointer parameter is not a speed fix: value versus pointer parameters belong to [go-functions](..\u002Fgo-functions\u002FSKILL.md#pointers-to-interfaces).\n\n---\n\n## String Concatenation\n\nBuild in a loop with `strings.Builder`, calling `Grow(n)` first when the final size is known.\n\n---\n\n## Caching\n\n> **Normative**: Cache what a profile shows is expensive and read far more\n> often than it changes. A cached fast call buys nothing and adds a staleness\n> bug.\n\n- **The key is every input the answer depends on**: the tenant, caller,\n  locale, or permissions it was computed for, including those that arrive in\n  `ctx`. A key of the user ID alone serves one tenant's record to another.\n  A loader that dedups within one request (a GraphQL DataLoader) is built per\n  request; shared by the process, it is a cache with no tenant in its key.\n- **One expiry rule, stated.** The TTL is the staleness the caller accepts. A\n  balance, a permission, or stock at checkout is not cached. A failed load is\n  returned and not kept. A write deletes the key after its transaction\n  commits and never stores the value it was handed: two writers that commit\n  in one order and set the cache in the other keep the older value until the\n  TTL. Only a load fills.\n- **Concurrent misses share one load**, or a cold hot key sends every waiting\n  request to the origin at once. Use `golang.org\u002Fx\u002Fsync\u002Fsingleflight` where the\n  module already requires `golang.org\u002Fx\u002Fsync`, otherwise the in-flight entry\n  below. The lock guards the map and is never held across the load, so one\n  slow key does not stall the rest. The load takes the first caller's `ctx`\n  values but not its cancellation (`context.WithoutCancel`), so a caller that\n  leaves fails no other waiter, and `load` sets its own deadline; the entry is\n  finished in a `defer`, so a panicking `load` does not leave its key loading\n  for good.\n- **Bounded**: a cap on the entry count, or a sweep of expired entries; a key\n  space the code does not bound (user IDs, query strings) needs one, since\n  replacing an expired entry on its next read never frees a key that is not\n  read again. A map that only grows is a leak, and a swept one keeps its\n  peak table: [go-data-structures](..\u002Fgo-data-structures\u002FSKILL.md#a-map-never-shrinks).\n  Interning repeated values is `unique.Make` (Go 1.23); a map of\n  `weak.Pointer` (Go 1.24) is not a cache, since its entries die at the next\n  GC and its keys stay unless `runtime.AddCleanup` deletes them.\n\n```go\ntype rateKey struct{ tenant, pair string } \u002F\u002F every input the rate depends on\ntype entry struct {\n\tdone chan struct{} \u002F\u002F closed once rate and err are set\n\trate float64\n\terr  error\n\tat   time.Time \u002F\u002F zero while loading\n}\ntype Rates struct {\n\tload    func(ctx context.Context, key rateKey) (float64, error)\n\tttl     time.Duration\n\tmu      sync.Mutex         \u002F\u002F guards entries; never held across load\n\tentries map[rateKey]*entry \u002F\u002F bounded: tenants times currency pairs\n}\nfunc (r *Rates) Get(ctx context.Context, key rateKey) (float64, error) {\n\tr.mu.Lock()\n\te, ok := r.entries[key]\n\tif ok && (e.at.IsZero() || time.Since(e.at) \u003C r.ttl) {\n\t\tr.mu.Unlock()\n\t\tselect {\n\t\tcase \u003C-e.done:\n\t\t\treturn e.rate, e.err\n\t\tcase \u003C-ctx.Done():\n\t\t\treturn 0, ctx.Err()\n\t\t}\n\t}\n\te = &entry{done: make(chan struct{}), err: errors.New(\"rates: load panicked\")}\n\tr.entries[key] = e\n\tr.mu.Unlock()\n\tdefer func() { \u002F\u002F also after a panic in load: waiters wake, the key is retried\n\t\tr.mu.Lock()\n\t\te.at = time.Now()\n\t\tif e.err != nil {\n\t\t\tdelete(r.entries, key) \u002F\u002F a failed load is not kept\n\t\t}\n\t\tr.mu.Unlock()\n\t\tclose(e.done)\n\t}()\n\te.rate, e.err = r.load(context.WithoutCancel(ctx), key) \u002F\u002F its values, not its cancel\n\treturn e.rate, e.err\n}\n```\n\n---\n\n## Benchmarking and Profiling\n\nA request to make Go code faster runs these steps in order, from the project.\nThe defaults above (`strconv` for a lone value, a capacity known at the call\nsite, `strings.Builder` in a loop) need none of them.\n\n1. **A benchmark of the path the caller runs**, before any production edit:\n   an existing `Benchmark*` that covers it, or a new one in\n   `*_bench_test.go`. Its inputs have production's size and variety — a cache\n   benchmark with one key measures only hits — and it uses `b.RunParallel`\n   when requests run concurrently. The benchmark is a sample of the workload,\n   not the specification: nothing the change adds is keyed to its inputs or\n   kept between its iterations.\n2. **Freeze the baseline** after step 1 and before the first production edit,\n   one package at a time; the snapshot keeps the test binary and the test\n   files as they are now. `--filter` names the step 1 benchmark:\n\n   ```bash\n   bash \"\u003Cinstalled-skill-dir>\u002Fscripts\u002Fbench-compare.sh\" --snapshot .perf-snap\u002F1 --filter '^BenchmarkX$' .\u002Fpath\u002Fto\u002Fpkg\n   ```\n\n   Run this and the verdict from the project root, each alone in its own Bash\n   call: no `cd`, `&&`, shell variable, or `echo $?` — the host asks approval\n   for those, and the script prints its own `verdict:` line. `.perf-snap\u002F` is\n   ignored by `go` patterns; delete it after the report.\n\n3. **Profile the benchmark and name where the time is**, as\n   [Read the Profile](#read-the-profile) says. The function a request names\n   (\"X looks slow\", \"speed up X\") is a guess this step checks, not the\n   target: under 5% of the profile it stays as it is however wasteful it\n   reads — making it free saves less than 5% — and the report gives its share\n   and where the time went instead.\n4. **One change, from the cheapest class** in [Fix Order](#fix-order).\n5. **The verdict decides**, run serially, never beside another benchmark:\n\n   ```bash\n   bash \"\u003Cinstalled-skill-dir>\u002Fscripts\u002Fbench-compare.sh\" --verdict .perf-snap\u002F1 --filter '^BenchmarkX$' .\u002Fpath\u002Fto\u002Fpkg\n   ```\n\n   With the same `--filter`, the verdict judges the path the request is\n   about: every other benchmark of the package costs about 25 s at the\n   defaults and raises the bar each row must clear. The cost is per matching\n   row, sub-benchmarks included: N rows take about N × 25 s, so past four\n   name one sub-benchmark in `--filter` or give the call a timeout above the\n   host's default (120 s in Claude Code). `keep` (exit 0) keeps the\n   change; `revert` reverts it; `noisy` raises\n   `--count` or `--benchtime` and asks once more, and a change is never kept\n   on `noisy`. A second `noisy` is reported as no measurable change: rerunning\n   until a `keep` appears picks the noise, not the change. A `keep` on `allocs\u002Fop` or `B\u002Fop` alone is a speedup only where the\n   profile spent its time in allocation or GC; otherwise it is reported as\n   fewer allocations. After a kept change, profile again and name the next\n   hotspot; chase it only within the request, and snapshot the kept code into\n   a new directory (`.perf-snap\u002F2`) before that next change: against the first snapshot, a\n   second change that is slower still reads `keep` on the first one's gain.\n   A last verdict against the first snapshot gives the total.\n6. **Guard an allocation win** with an [allocation test](#allocation-guard)\n   when the change exists to remove allocations.\n7. **Report** each kept change with its verdict line and the production lines\n   it added, and each reverted attempt with its reason, so the next change\n   does not try a dead idea again. \"Faster\" needs a `keep` on `sec\u002Fop`;\n   without a verdict the comparison is reported as skipped.\n\nA behavior-preserving refactor asks a different question — did anything get\nslower — and keeps `--save`\u002F`--baseline` with `benchstat`\n([go-code-refactor](..\u002Fgo-code-refactor\u002FSKILL.md)).\n[BENCHMARKS.md](references\u002FBENCHMARKS.md) reads benchstat output and profiles.\n\n### Read the Profile\n\n`go test -run '^$' -bench \u003Cname> -o .perf-snap\u002Fpkg.test -cpuprofile .perf-snap\u002Fcpu.prof .\u002Fpath\u002Fto\u002Fpkg`\n(step 2's `.perf-snap\u002F` keeps the test binary and the profile out of the\npackages, and a path with no shell variable needs no approval), then\n`go tool pprof -top -cum .perf-snap\u002Fcpu.prof`; the row decides the class of\nfix:\n\n| The profile shows | The time goes to | First move |\n|---|---|---|\n| a package function and what it calls: `slices.Index`, `strings.Fields`, `regexp.Compile`, a parse per call | repeated or superlinear work | do it once where its input changes; a set in place of a scan |\n| `runtime.mallocgc` above about 15% cumulative, or `gcBgMarkWorker` and `gcAssistAlloc` above about 5% | allocation and GC | `-memprofile`, then `pprof -sample_index=alloc_space`; fewer values on the heap per call |\n| `runtime.gcDrain` (`scanObject`, `scanSpan` under it) high while allocs\u002Fop is low | marking a large, pointer-dense live heap | values instead of `*T` in long-lived slices and maps, indexes instead of pointer links |\n| `sync.(*Mutex).Unlock` at the top of a `-mutexprofile`, or `sync.(*Mutex).Lock` in a `-blockprofile`, of a `RunParallel` benchmark | contention | a shorter critical section; per-key state behind a read-mostly map ([go-concurrency](..\u002Fgo-concurrency\u002FSKILL.md)) |\n| total samples far below the profile's duration | waiting on I\u002FO, a round trip per item, or a lock | an existing batch API; [go-database](..\u002Fgo-database\u002FSKILL.md) for a query per row |\n| a syscall (`syscall.Write`, `Syscall6`) at the top | one system call per small read or write | count calls per op: a `bufio.Writer`\u002F`bufio.Reader` or one batched call is class 1; decline only when each unit of work already makes one call |\n| `crypto\u002F*` or `compress\u002F*` doing the payload's own work, set up once | work the platform already does at speed | nothing in this code: report the share and decline |\n\n### Fix Order\n\nTake the first class that reaches the speedup asked for, and stop:\n\n1. Do less: work repeated per call moved to where its input changes, a\n   quadratic scan replaced by a set, one round trip per batch.\n2. Allocate less with what ships: a struct in place of `map[string]any`, one\n   reused `Encoder` or buffer, `strconv.Append*`, a capacity known at the\n   call site.\n3. Contend less: a shorter critical section, atomics for independent counters.\n4. More CPUs per request, only where CPUs sit idle under the real load — a\n   batch job, not a server where every CPU already serves a request: there a\n   fan-out is faster in a one-call benchmark and no faster in `RunParallel`.\n5. Hand-written replacements for the standard library (an encoder, an\n   escaper, a hash table), shards, cache-line padding, `unsafe`: each takes its\n   own verdict against the best change from the classes above, and the report\n   names the lines it added.\n\n### Allocation Guard\n\nA kept allocation win stays won through a test of the count, not of time.\n`AllocsPerRun` counts every goroutine's allocations, panics under parallel\ntests, and the race detector drops pooled objects, so the test runs alone and\noutside `-race`:\n\n```go\n\u002F\u002Fgo:build !race\n\npackage ledger\n\nimport (\n\t\"io\"\n\t\"testing\"\n)\n\nfunc TestWriteReportAllocs(t *testing.T) {\n\trows := sampleRows(t, 100)\n\tgot := testing.AllocsPerRun(20, func() {\n\t\tif err := WriteReport(io.Discard, rows); err != nil {\n\t\t\tt.Fatal(err)\n\t\t}\n\t})\n\tif got > 1 {\n\t\tt.Errorf(\"WriteReport(100 rows) = %v allocs\u002Fop, want \u003C= 1: one buffer, not one per row\", got)\n\t}\n}\n```\n\n### Benchmark discipline\n\n- Keep benchmarks in a file of their own beside the source, ordered to mirror\n  the functions they measure. Go only requires some `_test.go` file; the\n  `*_bench_test.go` suffix is this pack's convention, and an existing project\n  layout outranks it.\n- Implement competing variants in isolation, so each run measures one of them.\n- A comparison that straddles a toolchain bump measures the toolchain, not the\n  code — re-run the baseline on the new toolchain first.\n\n### Before reaching for a faster library\n\nCheck the standard library first — the iterator variants (`strings.SplitSeq`\nGo 1.24+, `maps.Keys` Go 1.23+) skip the intermediate slice without a new\ndependency. JSON is not such a lever on Go 1.27: `encoding\u002Fjson` already runs\non the v2 implementation (unmarshal about a third faster; marshal 15–70%\nslower than on 1.26, and `encoding\u002Fjson\u002Fv2.Marshal` runs at the same speed),\nso moving an import to `encoding\u002Fjson\u002Fv2` measures nothing, and a comparison\nacross the 1.26 → 1.27 bump measures the new engine. The JSON wins are in\nthe call site: pass a pointer (`json.Marshal(&v)`, `enc.Encode(&v)`) — a\nstruct passed by value costs one more allocation on 1.27 — one reused\n`Encoder` or buffer, a struct in place of `map[string]any`. See [go-packages](..\u002Fgo-packages\u002FSKILL.md) for the\ndependency ladder.\n\n---\n\n## Runtime Settings\n\nProcess-wide knobs (`GOMAXPROCS` under a cgroup limit, `GOGC`\u002F`GOMEMLIMIT`,\n`default.pgo`) are in [RUNTIME.md](references\u002FRUNTIME.md); library code never\ncalls `debug.SetGCPercent` or the other process-wide setters.\n\n---\n\n## Related Skills\n\n- [go-data-structures](..\u002Fgo-data-structures\u002FSKILL.md): slices, maps, arrays and their allocation semantics.\n- [go-concurrency](..\u002Fgo-concurrency\u002FSKILL.md): parallel work, `sync.Pool` for buffers.\n- [go-database](..\u002Fgo-database\u002FSKILL.md): a query per row, pools, and batching when the time is a round trip.\n- [go-http](..\u002Fgo-http\u002FSKILL.md): client reuse and timeouts when the time is waiting on a service.\n- [go-style-core](..\u002Fgo-style-core\u002FSKILL.md): whether an optimization is worth its readability cost.\n- [go-troubleshooting](..\u002Fgo-troubleshooting\u002FSKILL.md): a slow, leaking, or hanging program with no named hot path yet; profile capture and the symptom catalog live there.\n","# Go Performance Patterns\n\n> Compatibility: Baseline Go 1.27 (see [COMPATIBILITY.md](..\u002Fgo-style-core\u002Freferences\u002FCOMPATIBILITY.md)). `b.Loop()`\n> requires Go 1.24+; `encoding\u002Fjson\u002Fv2` Go 1.27+; cgroup-aware `GOMAXPROCS`\n> Go 1.25+.\n\n## Resource Routing\n\n- `scripts\u002Fbench-compare.sh` - Run when comparing benchmark results, saving baselines, or producing JSON benchmark metadata.\n- `scripts\u002Fbench-verdict.go` - The statistics helper `bench-compare.sh --verdict` builds and calls; `scripts\u002Fbench-verdict_test.go` holds its unit tests. Neither is run or read directly.\n- `references\u002FBENCHMARKS.md` - Read when writing benchmarks, using benchstat, or profiling with pprof.\n- `references\u002FSTRING-OPTIMIZATION.md` - Read when optimizing concatenation or memory retained by substrings.\n- `references\u002FRUNTIME.md` - Read when setting `GOMAXPROCS`, `GOGC`, `GOMEMLIMIT`, or a PGO profile, or removing `automaxprocs`.\n\nApply performance-specific guidance to measured bottlenecks, including retained\nmemory. Don't add allocations or complexity without evidence that it helps.\n\n---\n\n## Prefer strconv over fmt\n\nFor direct primitive conversions, prefer `strconv` by default; choosing it\nneeds no benchmark:\n\n```go\ns := strconv.Itoa(n)\n```\n\n---\n\n## Avoid Repeated String-to-Byte Conversions\n\nFor a measured repeated-conversion cost, reuse the bytes outside the loop.\nThe compiler may already eliminate the conversion allocation for a concrete\nwriter, so compare the actual call site:\n\n```go\ndata := []byte(\"Hello world\")\nfor b.Loop() { \u002F\u002F Go 1.24+\n    w.Write(data)\n}\n```\n\n---\n\n## Prefer Specifying Container Capacity\n\nPreallocate when the final size is known at the call site (`len(files)`, a fixed loop bound); otherwise measure before guessing a capacity — an oversized estimate retains memory the workload never uses.\n\n---\n\n## Pass Values\n\nA pointer parameter is not a speed fix: value versus pointer parameters belong to [go-functions](..\u002Fgo-functions\u002FSKILL.md#pointers-to-interfaces).\n\n---\n\n## String Concatenation\n\nBuild in a loop with `strings.Builder`, calling `Grow(n)` first when the final size is known.\n\n---\n\n## Caching\n\n> **Normative**: Cache what a profile shows is expensive and read far more\n> often than it changes. A cached fast call buys nothing and adds a staleness\n> bug.\n\n- **The key is every input the answer depends on**: the tenant, caller,\n  locale, or permissions it was computed for, including those that arrive in\n  `ctx`. A key of the user ID alone serves one tenant's record to another.\n  A loader that dedups within one request (a GraphQL DataLoader) is built per\n  request; shared by the process, it is a cache with no tenant in its key.\n- **One expiry rule, stated.** The TTL is the staleness the caller accepts. A\n  balance, a permission, or stock at checkout is not cached. A failed load is\n  returned and not kept. A write deletes the key after its transaction\n  commits and never stores the value it was handed: two writers that commit\n  in one order and set the cache in the other keep the older value until the\n  TTL. Only a load fills.\n- **Concurrent misses share one load**, or a cold hot key sends every waiting\n  request to the origin at once. Use `golang.org\u002Fx\u002Fsync\u002Fsingleflight` where the\n  module already requires `golang.org\u002Fx\u002Fsync`, otherwise the in-flight entry\n  below. The lock guards the map and is never held across the load, so one\n  slow key does not stall the rest. The load takes the first caller's `ctx`\n  values but not its cancellation (`context.WithoutCancel`), so a caller that\n  leaves fails no other waiter, and `load` sets its own deadline; the entry is\n  finished in a `defer`, so a panicking `load` does not leave its key loading\n  for good.\n- **Bounded**: a cap on the entry count, or a sweep of expired entries; a key\n  space the code does not bound (user IDs, query strings) needs one, since\n  replacing an expired entry on its next read never frees a key that is not\n  read again. A map that only grows is a leak, and a swept one keeps its\n  peak table: [go-data-structures](..\u002Fgo-data-structures\u002FSKILL.md#a-map-never-shrinks).\n  Interning repeated values is `unique.Make` (Go 1.23); a map of\n  `weak.Pointer` (Go 1.24) is not a cache, since its entries die at the next\n  GC and its keys stay unless `runtime.AddCleanup` deletes them.\n\n```go\ntype rateKey struct{ tenant, pair string } \u002F\u002F every input the rate depends on\ntype entry struct {\n\tdone chan struct{} \u002F\u002F closed once rate and err are set\n\trate float64\n\terr  error\n\tat   time.Time \u002F\u002F zero while loading\n}\ntype Rates struct {\n\tload    func(ctx context.Context, key rateKey) (float64, error)\n\tttl     time.Duration\n\tmu      sync.Mutex         \u002F\u002F guards entries; never held across load\n\tentries map[rateKey]*entry \u002F\u002F bounded: tenants times currency pairs\n}\nfunc (r *Rates) Get(ctx context.Context, key rateKey) (float64, error) {\n\tr.mu.Lock()\n\te, ok := r.entries[key]\n\tif ok && (e.at.IsZero() || time.Since(e.at) \u003C r.ttl) {\n\t\tr.mu.Unlock()\n\t\tselect {\n\t\tcase \u003C-e.done:\n\t\t\treturn e.rate, e.err\n\t\tcase \u003C-ctx.Done():\n\t\t\treturn 0, ctx.Err()\n\t\t}\n\t}\n\te = &entry{done: make(chan struct{}), err: errors.New(\"rates: load panicked\")}\n\tr.entries[key] = e\n\tr.mu.Unlock()\n\tdefer func() { \u002F\u002F also after a panic in load: waiters wake, the key is retried\n\t\tr.mu.Lock()\n\t\te.at = time.Now()\n\t\tif e.err != nil {\n\t\t\tdelete(r.entries, key) \u002F\u002F a failed load is not kept\n\t\t}\n\t\tr.mu.Unlock()\n\t\tclose(e.done)\n\t}()\n\te.rate, e.err = r.load(context.WithoutCancel(ctx), key) \u002F\u002F its values, not its cancel\n\treturn e.rate, e.err\n}\n```\n\n---\n\n## Benchmarking and Profiling\n\nA request to make Go code faster runs these steps in order, from the project.\nThe defaults above (`strconv` for a lone value, a capacity known at the call\nsite, `strings.Builder` in a loop) need none of them.\n\n1. **A benchmark of the path the caller runs**, before any production edit:\n   an existing `Benchmark*` that covers it, or a new one in\n   `*_bench_test.go`. Its inputs have production's size and variety — a cache\n   benchmark with one key measures only hits — and it uses `b.RunParallel`\n   when requests run concurrently. The benchmark is a sample of the workload,\n   not the specification: nothing the change adds is keyed to its inputs or\n   kept between its iterations.\n2. **Freeze the baseline** after step 1 and before the first production edit,\n   one package at a time; the snapshot keeps the test binary and the test\n   files as they are now. `--filter` names the step 1 benchmark:\n\n   ```bash\n   bash \"\u003Cinstalled-skill-dir>\u002Fscripts\u002Fbench-compare.sh\" --snapshot .perf-snap\u002F1 --filter '^BenchmarkX$' .\u002Fpath\u002Fto\u002Fpkg\n   ```\n\n   Run this and the verdict from the project root, each alone in its own Bash\n   call: no `cd`, `&&`, shell variable, or `echo $?` — the host asks approval\n   for those, and the script prints its own `verdict:` line. `.perf-snap\u002F` is\n   ignored by `go` patterns; delete it after the report.\n\n3. **Profile the benchmark and name where the time is**, as\n   [Read the Profile](#read-the-profile) says. The function a request names\n   (\"X looks slow\", \"speed up X\") is a guess this step checks, not the\n   target: under 5% of the profile it stays as it is however wasteful it\n   reads — making it free saves less than 5% — and the report gives its share\n   and where the time went instead.\n4. **One change, from the cheapest class** in [Fix Order](#fix-order).\n5. **The verdict decides**, run serially, never beside another benchmark:\n\n   ```bash\n   bash \"\u003Cinstalled-skill-dir>\u002Fscripts\u002Fbench-compare.sh\" --verdict .perf-snap\u002F1 --filter '^BenchmarkX$' .\u002Fpath\u002Fto\u002Fpkg\n   ```\n\n   With the same `--filter`, the verdict judges the path the request is\n   about: every other benchmark of the package costs about 25 s at the\n   defaults and raises the bar each row must clear. The cost is per matching\n   row, sub-benchmarks included: N rows take about N × 25 s, so past four\n   name one sub-benchmark in `--filter` or give the call a timeout above the\n   host's default (120 s in Claude Code). `keep` (exit 0) keeps the\n   change; `revert` reverts it; `noisy` raises\n   `--count` or `--benchtime` and asks once more, and a change is never kept\n   on `noisy`. A second `noisy` is reported as no measurable change: rerunning\n   until a `keep` appears picks the noise, not the change. A `keep` on `allocs\u002Fop` or `B\u002Fop` alone is a speedup only where the\n   profile spent its time in allocation or GC; otherwise it is reported as\n   fewer allocations. After a kept change, profile again and name the next\n   hotspot; chase it only within the request, and snapshot the kept code into\n   a new directory (`.perf-snap\u002F2`) before that next change: against the first snapshot, a\n   second change that is slower still reads `keep` on the first one's gain.\n   A last verdict against the first snapshot gives the total.\n6. **Guard an allocation win** with an [allocation test](#allocation-guard)\n   when the change exists to remove allocations.\n7. **Report** each kept change with its verdict line and the production lines\n   it added, and each reverted attempt with its reason, so the next change\n   does not try a dead idea again. \"Faster\" needs a `keep` on `sec\u002Fop`;\n   without a verdict the comparison is reported as skipped.\n\nA behavior-preserving refactor asks a different question — did anything get\nslower — and keeps `--save`\u002F`--baseline` with `benchstat`\n([go-code-refactor](..\u002Fgo-code-refactor\u002FSKILL.md)).\n[BENCHMARKS.md](references\u002FBENCHMARKS.md) reads benchstat output and profiles.\n\n### Read the Profile\n\n`go test -run '^$' -bench \u003Cname> -o .perf-snap\u002Fpkg.test -cpuprofile .perf-snap\u002Fcpu.prof .\u002Fpath\u002Fto\u002Fpkg`\n(step 2's `.perf-snap\u002F` keeps the test binary and the profile out of the\npackages, and a path with no shell variable needs no approval), then\n`go tool pprof -top -cum .perf-snap\u002Fcpu.prof`; the row decides the class of\nfix:\n\n| The profile shows | The time goes to | First move |\n|---|---|---|\n| a package function and what it calls: `slices.Index`, `strings.Fields`, `regexp.Compile`, a parse per call | repeated or superlinear work | do it once where its input changes; a set in place of a scan |\n| `runtime.mallocgc` above about 15% cumulative, or `gcBgMarkWorker` and `gcAssistAlloc` above about 5% | allocation and GC | `-memprofile`, then `pprof -sample_index=alloc_space`; fewer values on the heap per call |\n| `runtime.gcDrain` (`scanObject`, `scanSpan` under it) high while allocs\u002Fop is low | marking a large, pointer-dense live heap | values instead of `*T` in long-lived slices and maps, indexes instead of pointer links |\n| `sync.(*Mutex).Unlock` at the top of a `-mutexprofile`, or `sync.(*Mutex).Lock` in a `-blockprofile`, of a `RunParallel` benchmark | contention | a shorter critical section; per-key state behind a read-mostly map ([go-concurrency](..\u002Fgo-concurrency\u002FSKILL.md)) |\n| total samples far below the profile's duration | waiting on I\u002FO, a round trip per item, or a lock | an existing batch API; [go-database](..\u002Fgo-database\u002FSKILL.md) for a query per row |\n| a syscall (`syscall.Write`, `Syscall6`) at the top | one system call per small read or write | count calls per op: a `bufio.Writer`\u002F`bufio.Reader` or one batched call is class 1; decline only when each unit of work already makes one call |\n| `crypto\u002F*` or `compress\u002F*` doing the payload's own work, set up once | work the platform already does at speed | nothing in this code: report the share and decline |\n\n### Fix Order\n\nTake the first class that reaches the speedup asked for, and stop:\n\n1. Do less: work repeated per call moved to where its input changes, a\n   quadratic scan replaced by a set, one round trip per batch.\n2. Allocate less with what ships: a struct in place of `map[string]any`, one\n   reused `Encoder` or buffer, `strconv.Append*`, a capacity known at the\n   call site.\n3. Contend less: a shorter critical section, atomics for independent counters.\n4. More CPUs per request, only where CPUs sit idle under the real load — a\n   batch job, not a server where every CPU already serves a request: there a\n   fan-out is faster in a one-call benchmark and no faster in `RunParallel`.\n5. Hand-written replacements for the standard library (an encoder, an\n   escaper, a hash table), shards, cache-line padding, `unsafe`: each takes its\n   own verdict against the best change from the classes above, and the report\n   names the lines it added.\n\n### Allocation Guard\n\nA kept allocation win stays won through a test of the count, not of time.\n`AllocsPerRun` counts every goroutine's allocations, panics under parallel\ntests, and the race detector drops pooled objects, so the test runs alone and\noutside `-race`:\n\n```go\n\u002F\u002Fgo:build !race\n\npackage ledger\n\nimport (\n\t\"io\"\n\t\"testing\"\n)\n\nfunc TestWriteReportAllocs(t *testing.T) {\n\trows := sampleRows(t, 100)\n\tgot := testing.AllocsPerRun(20, func() {\n\t\tif err := WriteReport(io.Discard, rows); err != nil {\n\t\t\tt.Fatal(err)\n\t\t}\n\t})\n\tif got > 1 {\n\t\tt.Errorf(\"WriteReport(100 rows) = %v allocs\u002Fop, want \u003C= 1: one buffer, not one per row\", got)\n\t}\n}\n```\n\n### Benchmark discipline\n\n- Keep benchmarks in a file of their own beside the source, ordered to mirror\n  the functions they measure. Go only requires some `_test.go` file; the\n  `*_bench_test.go` suffix is this pack's convention, and an existing project\n  layout outranks it.\n- Implement competing variants in isolation, so each run measures one of them.\n- A comparison that straddles a toolchain bump measures the toolchain, not the\n  code — re-run the baseline on the new toolchain first.\n\n### Before reaching for a faster library\n\nCheck the standard library first — the iterator variants (`strings.SplitSeq`\nGo 1.24+, `maps.Keys` Go 1.23+) skip the intermediate slice without a new\ndependency. JSON is not such a lever on Go 1.27: `encoding\u002Fjson` already runs\non the v2 implementation (unmarshal about a third faster; marshal 15–70%\nslower than on 1.26, and `encoding\u002Fjson\u002Fv2.Marshal` runs at the same speed),\nso moving an import to `encoding\u002Fjson\u002Fv2` measures nothing, and a comparison\nacross the 1.26 → 1.27 bump measures the new engine. The JSON wins are in\nthe call site: pass a pointer (`json.Marshal(&v)`, `enc.Encode(&v)`) — a\nstruct passed by value costs one more allocation on 1.27 — one reused\n`Encoder` or buffer, a struct in place of `map[string]any`. See [go-packages](..\u002Fgo-packages\u002FSKILL.md) for the\ndependency ladder.\n\n---\n\n## Runtime Settings\n\nProcess-wide knobs (`GOMAXPROCS` under a cgroup limit, `GOGC`\u002F`GOMEMLIMIT`,\n`default.pgo`) are in [RUNTIME.md](references\u002FRUNTIME.md); library code never\ncalls `debug.SetGCPercent` or the other process-wide setters.\n\n---\n\n## Related Skills\n\n- [go-data-structures](..\u002Fgo-data-structures\u002FSKILL.md): slices, maps, arrays and their allocation semantics.\n- [go-concurrency](..\u002Fgo-concurrency\u002FSKILL.md): parallel work, `sync.Pool` for buffers.\n- [go-database](..\u002Fgo-database\u002FSKILL.md): a query per row, pools, and batching when the time is a round trip.\n- [go-http](..\u002Fgo-http\u002FSKILL.md): client reuse and timeouts when the time is waiting on a service.\n- [go-style-core](..\u002Fgo-style-core\u002FSKILL.md): whether an optimization is worth its readability cost.\n- [go-troubleshooting](..\u002Fgo-troubleshooting\u002FSKILL.md): a slow, leaking, or hanging program with no named hot path yet; profile capture and the symptom catalog live there.\n",{"name":5,"description":7,"allowed-tools":24},"Bash(bash ${CLAUDE_SKILL_DIR}\u002Fscripts\u002F*)","main","59ac8ac7a0dd394878aaa0a7a7ecbc227356739f","skills\u002Fgo-performance",2,"https:\u002F\u002Fgithub.com\u002Fh0rn3t\u002Fgolang-skills","https:\u002F\u002Fgithub.com\u002Fh0rn3t","2026-11-14 04:23:12",{"source":8,"skillName":5,"commands":33,"prompt":43,"zipAvailable":44},[34,37,40],{"tool":35,"command":36},"npx","npx skills add h0rn3t\u002Fgolang-skills --skill go-performance",{"tool":38,"command":39},"bunx","bunx skills add h0rn3t\u002Fgolang-skills --skill go-performance",{"tool":41,"command":42},"pnpm","pnpm dlx skills add h0rn3t\u002Fgolang-skills --skill go-performance","安装技能，技能地址：https:\u002F\u002Fgithub.com\u002Fh0rn3t\u002Fgolang-skills\u002Fblob\u002Fmain\u002Fskills\u002Fgo-performance\u002FSKILL.md",true,[46,52,56,60,66,70],{"path":47,"resourceType":48,"resourceTypeDesc":49,"sizeBytes":50,"sourceHtmlUrl":51},"references\u002FBENCHMARKS.md","REFERENCE","参考文档",6828,"https:\u002F\u002Fgithub.com\u002Fh0rn3t\u002Fgolang-skills\u002Fblob\u002Fmain\u002Fskills\u002Fgo-performance\u002Freferences\u002FBENCHMARKS.md",{"path":53,"resourceType":48,"resourceTypeDesc":49,"sizeBytes":54,"sourceHtmlUrl":55},"references\u002FRUNTIME.md",1945,"https:\u002F\u002Fgithub.com\u002Fh0rn3t\u002Fgolang-skills\u002Fblob\u002Fmain\u002Fskills\u002Fgo-performance\u002Freferences\u002FRUNTIME.md",{"path":57,"resourceType":48,"resourceTypeDesc":49,"sizeBytes":58,"sourceHtmlUrl":59},"references\u002FSTRING-OPTIMIZATION.md",1101,"https:\u002F\u002Fgithub.com\u002Fh0rn3t\u002Fgolang-skills\u002Fblob\u002Fmain\u002Fskills\u002Fgo-performance\u002Freferences\u002FSTRING-OPTIMIZATION.md",{"path":61,"resourceType":62,"resourceTypeDesc":63,"sizeBytes":64,"sourceHtmlUrl":65},"scripts\u002Fbench-compare.sh","SCRIPT","脚本",23767,"https:\u002F\u002Fgithub.com\u002Fh0rn3t\u002Fgolang-skills\u002Fblob\u002Fmain\u002Fskills\u002Fgo-performance\u002Fscripts\u002Fbench-compare.sh",{"path":67,"resourceType":62,"resourceTypeDesc":63,"sizeBytes":68,"sourceHtmlUrl":69},"scripts\u002Fbench-verdict_test.go",7734,"https:\u002F\u002Fgithub.com\u002Fh0rn3t\u002Fgolang-skills\u002Fblob\u002Fmain\u002Fskills\u002Fgo-performance\u002Fscripts\u002Fbench-verdict_test.go",{"path":71,"resourceType":62,"resourceTypeDesc":63,"sizeBytes":72,"sourceHtmlUrl":73},"scripts\u002Fbench-verdict.go",13464,"https:\u002F\u002Fgithub.com\u002Fh0rn3t\u002Fgolang-skills\u002Fblob\u002Fmain\u002Fskills\u002Fgo-performance\u002Fscripts\u002Fbench-verdict.go",[75,82,89,96,103,110],{"skillNo":76,"name":77,"nameZh":6,"description":78,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":79,"categories":80,"keywords":81,"publishedAt":19},"01M7BQEMJBPJWY6CCGVKW27SH0","go-troubleshooting","Use when investigating a bug or ticket in a Go service whose cause is unknown — wrong or missing results, tenant-specific behavior, a regression, stage\u002Fprod\u002FCI differences, a panic, hang, deadlock, leak, unexplained CPU\u002FRSS growth, or a flaky test. Also use for pasted stack traces, profiles, logs, or requests to find a Go issue's root cause, even without the word debug. Does not cover rewriting ticket text, implementing an already-diagnosed fix alone (use its topic skill), or optimizing a known bottleneck (see go-performance).","https:\u002F\u002Fgithub.com\u002Fh0rn3t\u002Fgolang-skills\u002Fblob\u002Fmain\u002Fskills\u002Fgo-troubleshooting\u002FSKILL.md",[],[],{"skillNo":83,"name":84,"nameZh":6,"description":85,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":86,"categories":87,"keywords":88,"publishedAt":19},"01M7BQEFVSRHNDND750SB69WD8","go-testing","Use when writing, reviewing, or improving Go test code — including table-driven tests, subtests, parallel tests, test helpers, test doubles, and assertions with cmp.Diff. Also use when a user asks to write a test for a Go function, even if they don't mention specific patterns like table-driven tests or subtests. Does not cover benchmark performance testing (see go-performance).","https:\u002F\u002Fgithub.com\u002Fh0rn3t\u002Fgolang-skills\u002Fblob\u002Fmain\u002Fskills\u002Fgo-testing\u002FSKILL.md",[],[],{"skillNo":90,"name":91,"nameZh":6,"description":92,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":93,"categories":94,"keywords":95,"publishedAt":19},"01M7BQEA2DRH6H6WFYNJYJJRQQ","go-style-core","Use when resolving Go style or language mechanics such as formatting, nesting, declarations, initialization, scope, shadowing, loops, switches, or enum zero values. API design, naming, errors, and tests have specialized skills.","https:\u002F\u002Fgithub.com\u002Fh0rn3t\u002Fgolang-skills\u002Fblob\u002Fmain\u002Fskills\u002Fgo-style-core\u002FSKILL.md",[],[],{"skillNo":97,"name":98,"nameZh":6,"description":99,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":100,"categories":101,"keywords":102,"publishedAt":19},"01M7BQE3D1H45ANCXAWCS55CDK","go-security","Use when writing or reviewing Go code that touches untrusted input, secrets, or credentials — SQL, shell, or template injection, path traversal, SSRF, cookies and security headers, password hashing, TLS settings, token comparison, or what may appear in a log line. Also use when a handler accepts a file name, URL, or command argument from a client, or when asked to find \"vulnerabilities\", even if the user never says \"security\". Does not cover the os.Root and crypto\u002Frand mechanics (see go-defensive) or the dependency CVE scan in the gate (see go-linting).","https:\u002F\u002Fgithub.com\u002Fh0rn3t\u002Fgolang-skills\u002Fblob\u002Fmain\u002Fskills\u002Fgo-security\u002FSKILL.md",[],[],{"skillNo":104,"name":105,"nameZh":6,"description":106,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":107,"categories":108,"keywords":109,"publishedAt":19},"01M7BQDZYHG2YRJA3J26HFPKR7","go-resilience","Use when handling Go dependency failures or overload with retries, backoff\u002Fjitter, budgets, idempotency, duplicate delivery, circuit breakers, bulkheads, rate limits, backpressure, or degradation. Unknown root causes belong to go-troubleshooting.","https:\u002F\u002Fgithub.com\u002Fh0rn3t\u002Fgolang-skills\u002Fblob\u002Fmain\u002Fskills\u002Fgo-resilience\u002FSKILL.md",[],[],{"skillNo":111,"name":112,"nameZh":6,"description":113,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":114,"categories":115,"keywords":116,"publishedAt":19},"01M7BQDRS36WFNPVPCX3DHN459","go-packages","Use when creating or splitting Go packages, organizing imports or dependencies, or structuring a new Go project. Individual identifier naming belongs to go-naming.","https:\u002F\u002Fgithub.com\u002Fh0rn3t\u002Fgolang-skills\u002Fblob\u002Fmain\u002Fskills\u002Fgo-packages\u002FSKILL.md",[],[]]