go-performance — скилл для Claude Code: ускоряет Go-код
Скилл для оптимизации Go: подсказывает, где заменить fmt на strconv, как задать ёмкость слайса и когда хватит strings.Builder.
npx skills add cxuu/golang-skills --skill go-performance -a claude-codeЧто делает go-performance
Скилл включается, когда вы просите ускорить Go-код, разбираете медленный участок или пишете бенчмарки. Он держит под рукой набор паттернов: strconv вместо fmt при конвертации чисел, однократный перевод строки в []byte вне цикла, ёмкость для слайсов и мап через make, передача значений вместо указателей. Для каждого паттерна есть таблица с числами — например, слайс с зарезервированной ёмкостью на 100M итераций даёт 0.21s против 2.48s без неё.
Внутри три ресурса. scripts/bench-compare.sh запускают, когда нужно сравнить результаты бенчмарков, сохранить базовую линию или выдать метаданные в JSON. references/BENCHMARKS.md читают при написании бенчмарков, работе с benchstat и профилировании через pprof. references/STRING-OPTIMIZATION.md — про конвертацию строк, конкатенацию и переходы между byte и string. Сам скилл советует применять эти приёмы только на горячем пути и не оптимизировать заранее.
Параллельные паттерны производительности сюда не входят — для горутин и sync.Pool есть отдельный go-concurrency. Перед тем как оставлять правку, скилл требует измерить эффект через bash scripts/bench-compare.sh и сохранять только те оптимизации, где прирост виден. Это повод не тащить в код микрооптимизацию, которая ничего не дала на реальных данных.
Какие задачи решает
- заменить
fmt.Sprintнаstrconv.Itoaв узком месте - вынести перевод строки в
[]byteза пределы цикла - задать ёмкость слайса перед серией
append - собрать строку в цикле через
strings.Builderвместо+= - сравнить бенчмарки до и после правки
Примеры запросов агенту
- посмотри горячий путь в этом обработчике и предложи, что ускорить
- в цикле копится строка через
+=, перепиши наstrings.Builder - прогони бенчмарки до и после и покажи разницу
Как установить go-performance
1Через Skills CLI (Vercel)
npx skills add cxuu/golang-skills --skill go-performance -a claude-code2Вручную: положить файлы
~/.claude/skills/go-performance/SKILL.mdПапка скилла целиком; для одного проекта — .claude/skills/go-performance/
1Через Skills CLI (Vercel)
npx skills add cxuu/golang-skills --skill go-performance -a codex2Вручную: положить файлы
.agents/skills/go-performance/SKILL.mdДля всех проектов — ~/.agents/skills/
1Через Skills CLI (Vercel)
npx skills add cxuu/golang-skills --skill go-performance -a cursor2Вручную: положить файлы
.cursor/skills/go-performance/SKILL.mdCursor читает и .agents/skills/, и .claude/skills/
1GitHub CLI
gh skill install cxuu/golang-skills go-performance2Вручную: положить файлы
.github/skills/go-performance/SKILL.md1Через Skills CLI (Vercel)
npx skills add cxuu/golang-skills --skill go-performance -a gemini-cli2Командой платформы
gemini skills install https://github.com/cxuu/golang-skills --path skills/go-performanceВручную: положить файлы
.devin/skills/go-performance/SKILL.mdСтарый путь .windsurf/skills/ тоже читается
Через Skills CLI (Vercel)
npx skills add cxuu/golang-skills --skill go-performance -a opencodeClaude.ai
Упакуйте папку в zip и загрузите в Settings → Capabilities → Skills
По шагам, с командами для каждой платформы: Как установить скилл в Claude Code: пять способов
Из того же набора19
Похожие
Рядом в теме «Языки программирования»
Все скиллы по теме «Языки программирования» →Вопросы о go-performance
Как установить go-performance в Claude?
Выполните npx skills add cxuu/golang-skills --skill go-performance -a claude-code. После этого файл скилла лежит в ~/.claude/skills/go-performance/SKILL.md.
Что делает go-performance?
Даёт агенту набор паттернов оптимизации Go: замена fmt на strconv, работа с []byte вне цикла, ёмкость контейнеров, передача значений. Плюс ссылки на бенчмарки и профилирование.
Покрывает ли скилл горутины и параллельную работу?
Нет, параллельные паттерны производительности вынесены в отдельный скилл go-concurrency. Здесь только однопоточные приёмы и бенчмарки.
Исходный текст
SKILL.md · Apache-2.0
---
name: go-performance
description: Use when optimizing Go code, investigating slow performance, or writing performance-critical sections. Also use when a user mentions slow Go code, string concatenation in loops, or asks about benchmarking, even if the user doesn't explicitly mention performance patterns. Does not cover concurrent performance patterns (see go-concurrency).
allowed-tools: Bash(bash:*)
---
# Go Performance Patterns
## Resource Routing
- `scripts/bench-compare.sh` - Run when comparing benchmark results, saving baselines, or producing JSON benchmark metadata.
- `references/BENCHMARKS.md` - Read when writing benchmarks, using benchstat, or profiling with pprof.
- `references/STRING-OPTIMIZATION.md` - Read when optimizing string conversion, concatenation, or byte/string boundaries.
Performance-specific guidelines apply only to the **hot path**. Don't prematurely optimize—focus these patterns where they matter most.
---
## Prefer strconv over fmt
When converting primitives to/from strings, `strconv` is faster than `fmt`:
```go
s := strconv.Itoa(rand.Int()) // ~2x faster than fmt.Sprint()
```
| Approach | Speed | Allocations |
|----------|-------|-------------|
| `fmt.Sprint` | 143 ns/op | 2 allocs/op |
| `strconv.Itoa` | 64.2 ns/op | 1 allocs/op |
---
## Avoid Repeated String-to-Byte Conversions
Convert a fixed string to `[]byte` once outside the loop:
```go
data := []byte("Hello world")
for b.Loop() { // Go 1.24+; use b.N loops only for older Go
w.Write(data) // ~7x faster than []byte("...") each iteration
}
```
---
## Prefer Specifying Container Capacity
Specify container capacity where possible to allocate memory up front. This minimizes subsequent allocations from copying and resizing as elements are added.
### Map Capacity Hints
Provide capacity hints when initializing maps with `make()`:
```go
m := make(map[string]os.DirEntry, len(files))
```
**Note**: Unlike slices, map capacity hints do not guarantee complete preemptive allocation—they approximate the number of hashmap buckets required.
### Slice Capacity
Provide capacity hints when initializing slices with `make()`, particularly when appending:
```go
data := make([]int, 0, size)
```
Unlike maps, slice capacity is **not a hint**—the compiler allocates exactly that much memory. Subsequent `append()` operations incur zero allocations until capacity is reached.
| Approach | Time (100M iterations) |
|----------|------------------------|
| No capacity | 2.48s |
| With capacity | 0.21s |
The capacity version is **~12x faster** due to zero reallocations during append.
---
## Pass Values
Don't pass pointers as function arguments just to save a few bytes. If a function refers to its argument `x` only as `*x` throughout, then the argument shouldn't be a pointer.
```go
func process(s string) { // not *string — strings are small fixed-size headers
fmt.Println(s)
}
```
**Common pass-by-value types**: `string`, `io.Reader`, small structs.
**Exceptions**:
- Large structs where copying is expensive
- Small structs that might grow in the future
---
## String Concatenation
Choose the right strategy based on complexity:
| Method | Best For |
|--------|----------|
| `+` | Few strings, simple concat |
| `fmt.Sprintf` | Formatted output with mixed types |
| `strings.Builder` | Loop/piecemeal construction |
| `strings.Join` | Joining a slice |
| Backtick literal | Constant multi-line text |
---
## Benchmarking and Profiling
Always measure before and after optimizing. Use Go's built-in benchmark framework and profiling tools.
```bash
go test -bench=. -benchmem -count=10 ./...
```
> **Validation**: After applying optimizations, run `bash scripts/bench-compare.sh` to measure the actual impact. Only keep optimizations with measurable improvement.
---
## Quick Reference
| Pattern | Bad | Good | Improvement |
|---------|-----|------|-------------|
| Int to string | `fmt.Sprint(n)` | `strconv.Itoa(n)` | ~2x faster |
| Repeated `[]byte` | `[]byte("str")` in loop | Convert once outside | ~7x faster |
| Map initialization | `make(map[K]V)` | `make(map[K]V, size)` | Fewer allocs |
| Slice initialization | `make([]T, 0)` | `make([]T, 0, cap)` | ~12x faster |
| Small fixed-size args | `*string`, `*io.Reader` | `string`, `io.Reader` | No indirection |
| Simple string join | `s1 + " " + s2` | (already good) | Use `+` for few strings |
| Loop string build | Repeated `+=` | `strings.Builder` | O(n) vs O(n²) |
---
## Related Skills
- **Data structures**: See [go-data-structures](../go-data-structures/SKILL.md) when choosing between slices, maps, and arrays, or understanding allocation semantics
- **Declaration patterns**: See [go-declarations](../go-declarations/SKILL.md) when using `make` with capacity hints or initializing maps and slices
- **Concurrency**: See [go-concurrency](../go-concurrency/SKILL.md) when parallelizing work across goroutines or using sync.Pool for buffer reuse
- **Style principles**: See [go-style-core](../go-style-core/SKILL.md) when deciding whether an optimization is worth the readability cost
© cxuu · Apache-2.0 · cxuu/golang-skills