optimizing-code
Compare original and translation side by side
🇺🇸
Original
English🇨🇳
Translation
ChineseOptimizing Code
代码优化
The Optimization Hat
优化准则
When optimizing, you improve performance without changing behavior. Always measure before and after.
进行优化时,你需要在不改变行为的前提下提升性能。优化前后务必进行测量。
Golden Rules
黄金法则
- Measure First: Never optimize without a benchmark
- Profile Before Guessing: Find the actual bottleneck
- Optimize the Right Thing: Focus on the critical path
- Measure After: Verify the optimization worked
- 先测量(Measure First):绝不进行无Benchmark的优化
- 先Profiling再猜测(Profile Before Guessing):找到真正的性能瓶颈
- 优化正确的部分(Optimize the Right Thing):聚焦关键路径
- 后测量(Measure After):验证优化是否有效
Workflows
工作流程
- Benchmark: Establish baseline performance metrics
- Profile: Identify the actual bottleneck
- Hypothesize: What optimization will help?
- Implement: Make the change
- Measure: Verify improvement
- Document: Record the optimization and results
- Benchmark:建立基准性能指标
- Profiling:识别真正的性能瓶颈
- 提出假设:哪种优化方法会有效?
- 实施:进行修改
- 测量:验证优化效果
- 文档记录:记录优化内容和结果
Common Optimizations
常见优化手段
Algorithm Complexity
算法复杂度
- Replace O(n²) with O(n log n) or O(n)
- Use appropriate data structures (Set for lookups, Map for key-value)
- 用O(n log n)或O(n)复杂度的算法替代O(n²)
- 使用合适的数据结构(Set用于查找,Map用于键值对存储)
Caching
缓存
typescript
// Memoization
const cache = new Map<string, Result>();
function expensiveCalculation(input: string): Result {
if (cache.has(input)) {
return cache.get(input)!;
}
const result = /* expensive work */;
cache.set(input, result);
return result;
}typescript
// Memoization
const cache = new Map<string, Result>();
function expensiveCalculation(input: string): Result {
if (cache.has(input)) {
return cache.get(input)!;
}
const result = /* expensive work */;
cache.set(input, result);
return result;
}Database Queries
数据库查询
- Add indexes for frequently queried columns
- Avoid N+1 queries (use eager loading)
- Use pagination for large result sets
- 为频繁查询的字段添加索引
- 避免N+1查询(使用预加载)
- 对大型结果集使用分页
Memory
内存优化
- Avoid creating unnecessary objects in loops
- Use streaming for large files
- Release references when done
- 避免在循环中创建不必要的对象
- 对大文件使用流处理
- 不再使用时释放引用
Profiling Tools
Profiling工具
bash
undefinedbash
undefinedNode.js
Node.js
node --prof app.js
node --prof-process isolate-*.log
node --prof app.js
node --prof-process isolate-*.log
Python
Python
python -m cProfile -s cumtime script.py
python -m cProfile -s cumtime script.py
Go
Go
go test -bench=. -cpuprofile=cpu.prof
go tool pprof cpu.prof
undefinedgo test -bench=. -cpuprofile=cpu.prof
go tool pprof cpu.prof
undefinedAnti-Patterns to Avoid
需避免的反模式
- Premature optimization (no benchmark)
- Micro-optimizations (negligible impact)
- Optimizing cold paths
- Sacrificing readability for minor gains
- 过早优化(无Benchmark)
- 微优化(影响可忽略)
- 优化冷路径
- 为微小收益牺牲可读性