정보
이 스킬은 Go 코드의 성능 병목 현상과 최적화 기회를 식별하며, 메모리 할당, 문자열 처리, 자료구조 사용에 중점을 둡니다. 슬라이스 사전 할당, sync.Pool 사용법, pprof 프로파일링 가이드와 같은 구체적인 기법을 제공합니다. Go 애플리케이션의 핫 경로를 벤치마크하거나 프로파일링, 최적화할 필요가 있을 때 사용하세요.
빠른 설치
Claude Code
추천npx skills add eduardo-sl/go-agent-skills -a claude-code/plugin add https://github.com/eduardo-sl/go-agent-skillsgit clone https://github.com/eduardo-sl/go-agent-skills.git ~/.claude/skills/go-performance-reviewClaude Code에서 이 명령을 복사하여 붙여넣어 스킬을 설치하세요
문서
Go Performance Review
Profile first, optimize second. Never optimize without a benchmark proving the problem.
1. Allocation Reduction
Prefer strconv over fmt for primitive conversions:
// ✅ Good — zero allocations for simple conversions
s := strconv.Itoa(42)
s := strconv.FormatFloat(3.14, 'f', 2, 64)
// ❌ Bad — fmt.Sprintf allocates
s := fmt.Sprintf("%d", 42)
Avoid unnecessary string-to-byte conversions:
// ✅ Good — use strings.Builder for concatenation
var b strings.Builder
for _, s := range parts {
b.WriteString(s)
}
result := b.String()
// ❌ Bad — repeated concatenation allocates on every +
result := ""
for _, s := range parts {
result += s
}
Preallocate slices and maps when size is known:
// ✅ Good — single allocation
users := make([]User, 0, len(ids))
for _, id := range ids {
users = append(users, getUser(id))
}
// ✅ Good — map with capacity hint
lookup := make(map[string]User, len(users))
// ❌ Bad — repeated growing
var users []User // starts at 0, grows via doubling
Use sync.Pool for frequently allocated, short-lived objects:
var bufPool = sync.Pool{
New: func() interface{} {
return new(bytes.Buffer)
},
}
func process(data []byte) string {
buf := bufPool.Get().(*bytes.Buffer)
defer func() {
buf.Reset()
bufPool.Put(buf)
}()
buf.Write(data)
return buf.String()
}
2. Hot Path Optimizations
Avoid interface conversions in tight loops:
// ✅ Good — concrete type in loop
func sum(vals []int64) int64 {
var total int64
for _, v := range vals {
total += v
}
return total
}
// ❌ Bad — interface{} causes boxing/unboxing
func sum(vals []interface{}) int64 { ... }
Avoid reflect in performance-critical paths:
If you need reflection-like behavior at scale, use code generation
(go generate, stringer, protocol buffers).
Reduce pointer chasing:
// ✅ Good — contiguous memory, cache-friendly
type Points struct {
X []float64
Y []float64
}
// ❌ Slower — pointer chasing per element
type Points []*Point
3. Map Performance
// ✅ Use capacity hints
m := make(map[string]int, expectedSize)
// ✅ For read-heavy concurrent access, use sync.Map
// But ONLY when keys are stable — sync.Map has higher overhead
// for writes than a mutex-protected map.
// ✅ For fixed key sets, consider using a slice with index mapping
// instead of a map.
4. Benchmarking
ALWAYS write benchmarks before and after optimization:
func BenchmarkFoo(b *testing.B) {
// Setup outside the loop
input := generateInput()
b.ResetTimer()
for i := 0; i < b.N; i++ {
result = Foo(input) // assign to package-level var to prevent elision
}
}
// Package-level var prevents compiler from eliminating the call
var result string
Run benchmarks with memory profiling:
go test -bench=BenchmarkFoo -benchmem -count=5 ./...
Compare before/after with benchstat:
go test -bench=. -count=10 > old.txt
# make changes
go test -bench=. -count=10 > new.txt
benchstat old.txt new.txt
5. Profiling
CPU profiling:
go test -cpuprofile=cpu.prof -bench=BenchmarkFoo .
go tool pprof cpu.prof
Memory profiling:
go test -memprofile=mem.prof -bench=BenchmarkFoo .
go tool pprof -alloc_space mem.prof
HTTP server profiling (import net/http/pprof):
import _ "net/http/pprof"
// Access at http://localhost:6060/debug/pprof/
go func() {
log.Println(http.ListenAndServe("localhost:6060", nil))
}()
6. High-Throughput Logging
log/slog is the right default for most services. But when benchmarks show
logging is a bottleneck (high-frequency hot paths, >100k log lines/sec),
consider zero-allocation loggers.
When slog is not enough:
// slog allocates per log call — fine for most services
slog.Info("request handled",
slog.String("method", method),
slog.Int("status", status),
)
// In hot paths where benchmarks prove logging is a bottleneck,
// use zap's zero-allocation core:
logger, _ := zap.NewProduction()
logger.Info("request handled",
zap.String("method", method),
zap.Int("status", status),
)
// zap avoids allocations by using a field pool and typed fields
Decision tree:
| Scenario | Logger |
|---|---|
| General service logging | log/slog (stdlib, zero dependencies) |
| High-frequency hot path (>100k lines/sec) | go.uber.org/zap (zero-alloc) |
| Extreme throughput with JSON | github.com/rs/zerolog (zero-alloc JSON) |
Best of both worlds — use zap as slog backend:
// Use slog API everywhere, backed by zap's performance
zapLogger, _ := zap.NewProduction()
slogHandler := zapslog.NewHandler(zapLogger.Core(), nil)
logger := slog.New(slogHandler)
// Code uses standard slog API — can swap backend without changing callers
logger.Info("request handled",
slog.String("method", method),
slog.Int("status", status),
)
Logging anti-patterns in hot paths:
// ❌ Bad — logging inside tight loop
for _, item := range millions {
slog.Info("processing item", slog.String("id", item.ID))
process(item)
}
// ✅ Good — sample or batch log
for i, item := range millions {
process(item)
if i%10000 == 0 {
slog.Info("progress", slog.Int("processed", i), slog.Int("total", len(millions)))
}
}
// ✅ Good — log summary after loop
slog.Info("batch complete", slog.Int("count", len(millions)))
NEVER switch loggers without a benchmark proving the need.
slog is fast enough for the vast majority of Go services.
7. Common Anti-Patterns
| Anti-Pattern | Fix |
|---|---|
fmt.Sprintf for simple int→string | strconv.Itoa |
| String concatenation in loop | strings.Builder |
| Slice without preallocation | make([]T, 0, n) |
| Map without capacity hint | make(map[K]V, n) |
regexp.Compile inside function | Compile once at package level |
json.Marshal in hot path | Use code-gen (easyjson, sonic) |
| Logging in tight loop | Batch or sample |
defer in very tight inner loop | Manual cleanup (rare, benchmark first) |
Important Caveat
Most Go code is not performance-critical. Readability and correctness ALWAYS take priority over micro-optimizations. Only apply these patterns when:
- A benchmark proves this code path is a bottleneck
- The optimization is significant (>10% improvement)
- The resulting code remains readable and maintainable
Premature optimization is still the root of all evil, even in Go.
GitHub 저장소
자주 묻는 질문
go-performance-review Skill이란 무엇인가요?
go-performance-review은(는) eduardo-sl이(가) 만든 Claude Skill입니다. Skill은 Claude가 필요할 때 불러오는 지침과 리소스를 묶어 추가 프롬프트 없이 go-performance-review 관련 작업을 수행할 수 있게 합니다.
go-performance-review은(는) 어떻게 설치하나요?
이 페이지의 설치 명령을 사용하세요. go-performance-review을(를) Claude Code 플러그인으로 추가하거나 저장소를 skills 디렉터리에 복제한 다음 Claude를 다시 시작해 Skill을 불러옵니다.
go-performance-review은(는) 어떤 카테고리에 속하나요?
go-performance-review은(는) 개발 카테고리에 속합니다.
go-performance-review은(는) 무료로 사용할 수 있나요?
네. go-performance-review은(는) AIMCP에 등록되어 있으며 무료로 설치할 수 있습니다.
연관 스킬
qmd는 BM25, 벡터 임베딩, 재순위화를 결합한 하이브리드 검색을 통해 로컬 파일을 색인화하고 검색할 수 있는 로컬 검색 및 색인화 CLI 도구입니다. 명령줄 사용과 Claude 통합을 위한 MCP(Model Context Protocol) 모드를 모두 지원합니다. 이 도구는 임베딩에 Ollama를 사용하고 색인을 로컬에 저장하여 터미널에서 직접 문서나 코드베이스를 검색하는 데 이상적입니다.
이 스킬은 각 독립적인 작업마다 새로운 하위 에이전트를 배치하고 작업 사이에 코드 리뷰를 진행하여 구현 계획을 실행합니다. 이 리뷰 프로세스를 통해 품질 게이트를 유지하면서 빠른 반복 작업을 가능하게 합니다. 동일한 세션 내에서 대부분 독립적인 작업을 진행할 때 내장된 품질 검증과 함께 지속적인 진행을 보장하기 위해 사용하세요.
mcporter 스킬은 개발자가 Claude에서 직접 Model Context Protocol(MCP) 서버를 관리하고 호출할 수 있도록 합니다. 이 스킬은 사용 가능한 서버를 나열하고, 인수를 사용해 해당 서버의 도구를 호출하며, 인증 및 데몬 생명주기를 처리하는 명령어를 제공합니다. 개발 워크플로우에서 MCP 서버 기능을 통합하고 테스트할 때 이 스킬을 사용하세요.
이 스킬은 A2A 프로토콜을 사용하여 Vertex AI ADK 에이전트를 배포하고 오케스트레이션하며, AgentCard 검색, 작업 제출, 코드 실행 샌드박스 및 메모리 뱅크와 같은 지원 도구를 관리합니다. Python, Java 또는 Go 언어로 순차, 병렬 또는 루프 오케스트레이션 패턴을 갖춘 다중 에이전트 시스템 구축을 가능하게 합니다. Google Cloud에서 ADK 에이전트 배포 또는 에이전트 워크플로우 오케스트레이션을 요청받았을 때 사용하세요.
