AgentSkillsCN

perf-review-guide

在审查或编写性能敏感型代码时使用此技能。为Kotlin、Python以及TypeScript/JavaScript中的常见性能反模式与优化策略提供快速参考。

SKILL.md
--- frontmatter
name: perf-review-guide
description: Use this skill when reviewing or writing performance-sensitive code. Provides quick reference for common performance anti-patterns and optimization strategies across Kotlin, Python, and TypeScript/JavaScript.

Performance Review Quick Reference

This skill provides a condensed checklist for identifying performance anti-patterns during code review or development.

When to Activate

  • Reviewing code that handles high throughput or low-latency requirements
  • Writing or modifying database queries, batch processing, or API handlers
  • Working with large datasets, collections, or serialization
  • Changing concurrency, threading, or async patterns
  • Noticing potential memory leaks or excessive object allocation
  • Optimizing slow endpoints or background jobs

Core Principles

1. Measure First

Never optimize without profiling. Use benchmarks to confirm bottlenecks before refactoring.

2. Focus on Hot Paths

Optimize code that runs frequently (request handlers, loops, batch jobs). Cold paths (startup, config loading) rarely matter.

3. Readability vs Performance

Only sacrifice readability when profiling proves measurable impact. Premature optimization causes maintenance burden.

Quick Reference by Category

1. Object Creation & Memory

Anti-PatternFixLanguages
New ObjectMapper per callSingleton companion objectKotlin
Missing __slots__ on data classesAdd __slots__Python
new RegExp() in functionsModule-level constantTS/JS
Closure retaining large objectsExtract needed values onlyTS/JS

2. Loops & Algorithms

Anti-PatternFixLanguages
DB call inside loop (N+1)Batch query (findAllById)All
String concatenation in loopjoinToString / StringBuilderKotlin
List comprehension for sumGenerator expressionPython
DOM append in loopDocumentFragment batchingTS/JS

3. I/O & Network

Anti-PatternFixLanguages
N+1 lazy loading@EntityGraph / fetch joinKotlin
@Transactional wrapping HTTP callsNarrow transaction scopeKotlin
Sequential HTTP requestsasyncio.gather / Promise.allPython/TS
Loading entire file into memoryStream responseTS/JS

4. Serialization

Anti-PatternFixLanguages
New ObjectMapper per requestInject or companion objectKotlin
json.loads/dumps (stdlib)orjson (3-10x faster)Python
JSON.stringify for comparisonDeep equality (isEqual)TS/JS
Reflection-based DTO mappingMapStruct (compile-time)Kotlin

5. Concurrency

Anti-PatternFixLanguages
@Synchronized on entire methodMinimize critical sectionKotlin
runBlocking on request threadsuspend funKotlin
ThreadPoolExecutor for CPU workProcessPoolExecutorPython
Heavy computation on main threadWorker threadsTS/JS
Unbounded Promise.allp-limit concurrency controlTS/JS

6. Collections

Anti-PatternFixLanguages
List.contains() in loopConvert to HashSetKotlin
list.pop(0)collections.dequePython
Array for large numeric dataTypedArrayTS/JS
Object as dynamic mapMap for frequent mutationsTS/JS

7. Caching

Anti-PatternFixLanguages
DB query for rarely-changing dataCaffeine cache with TTLKotlin
Repeated expensive computation@cached / lru_cachePython
Strong reference cacheWeakRef-based cacheTS/JS
Recomputing derived data each renderuseMemoReact/TS

8. Logging & Exceptions

Anti-PatternFixLanguages
String concat in disabled log levelLambda-based logger.debug { }Kotlin
f-string in debug log%s lazy formattingPython
Exceptions for expected flowResult patternKotlin
Error creation for flow controlReturn validation resultTS/JS

9. Elasticsearch / Search

Anti-PatternFixLanguages
Single-document indexing in loopBulk APIAll
from/size deep paginationsearch_afterAll
Expensive aggregation every requestCache with TTLAll
Same analyzer for index & searchSeparate analyzersAll

Top 5 Most Common Anti-Patterns

These are the patterns most frequently encountered in production code reviews:

1. N+1 Queries

kotlin
// BAD
ids.map { userRepository.findById(it) }
// GOOD
userRepository.findAllById(ids)

2. ObjectMapper / JSON Serializer Per Call

kotlin
// BAD
val mapper = ObjectMapper()
// GOOD
companion object { private val mapper = jacksonObjectMapper() }

3. Sequential I/O Where Parallel Is Possible

typescript
// BAD
const a = await fetchA(); const b = await fetchB()
// GOOD
const [a, b] = await Promise.all([fetchA(), fetchB()])

4. Wrong Collection Type for Lookups

python
# BAD: O(n) per check
if item in large_list: ...
# GOOD: O(1) per check
if item in large_set: ...

5. Oversized Transaction Scope

kotlin
// BAD: @Transactional wrapping external HTTP call
// GOOD: Split into DB-only transaction + separate HTTP call

Severity Guide

SeverityWhen to Flag
CriticalOOM risk, deadlock, production outage potential
HighMeasurable latency/throughput degradation
MediumSuboptimal but functional, improvement opportunity
LowMinor optimization, nice-to-have

Integration with Other Tools

  • Use /perf-review [target] command for structured analysis with full report
  • Use /analyze --focus performance for broader architecture-level review
  • The perf-reviewer agent contains the complete checklist with all code examples
  • This skill provides quick reference during regular development

Remember: Performance matters most in hot paths. Always profile before optimizing, and keep code readable unless the benchmark proves otherwise.