效能最佳化最佳實踐
用Claude Code開發時,效能直接影響效率。響應慢讓人心煩,最佳化後的工作流能讓速度快2-5倍。下面聊聊怎麼榨乾Claude Code的效能。
為什麼要最佳化效能
實際體驗差異
響應時間的影響:
- 小於2秒: 順手,不中斷思路
- 2-5秒: 還行,偶爾走神
-
5秒: 煩人,效率降一半
錢的問題:
- API按token收費,廢話多就燒錢
- 等待的時間也是成本
- 重複操作浪費資源
實際對比
最佳化前:
重构一个React组件
├─ 读取5个文件 (20秒)
├─ 理解依赖 (15秒)
├─ 生成代码 (25秒)
├─ 修复错误 (18秒)
└─ 总计: 78秒,被打断好几次
最佳化後:
重构同一个组件
├─ 精确读取相关文件 (8秒)
├─ 一次性完成 (12秒)
└─ 总计: 20秒,思路连贯
省了74%的時間
加快響應速度
1. 請求要說清楚
別說 模糊的話
不好的例子:
你: 帮我看看这个组件
Claude: 好的,让我先读取这个文件...
[读取了整个文件,2000行]
Claude: 这是一个大型组件,你想要我做什么呢?
你: 优化一下性能
Claude: 好的,让我分析性能问题...
[花很长时间分析整个组件]
好的例子:
你: 优化UserProfile组件性能:
1. 用React.memo包装
2. searchValue状态提到父组件
3. useMemo缓存计算结果
只改src/components/UserProfile.tsx
Claude: 明白了,针对性地优化这三点...
[直接执行]
使用明確的上下文限定
最佳化前:
你: 修复所有的类型错误
Claude: [扫描整个项目,分析所有文件]
最佳化後:
你: 修复src/api/users.ts中的类型错误
Claude: [只读取这一个文件]
效能提升: 3-5倍
2. 批次操作最佳化
合併相關請求
低效方式:
你: 创建Button组件
Claude: [创建Button.tsx] (10秒)
你: 添加类型定义
Claude: [添加Button.types.ts] (8秒)
你: 添加样式文件
Claude: [添加Button.module.css] (7秒)
你: 创建index导出文件
Claude: [创建index.ts] (6秒)
总计: 31秒,4次等待
高效方式:
你: 创建完整的Button组件套件,包括:
1. Button.tsx主组件
2. Button.types.ts类型定义
3. Button.module.css样式文件
4. index.ts导出文件
Claude: [一次性创建所有文件] (15秒)
总计: 15秒,1次等待
效能提升: 52%
批次檔案操作
## 批量操作模板
### 批量读取
不要分多次读取文件:
❌ 你: "读取utils.ts"
❌ 你: "读取helpers.ts"
❌ 你: "读取constants.ts"
✅ 你: "同时读取这三个文件: utils.ts, helpers.ts, constants.ts"
### 批量修改
不要分多次修改相关文件:
❌ 你: "修改API配置"
❌ 你: "更新类型定义"
❌ 你: "修改调用处"
✅ 你: "重构API调用:
1. 更新src/config/api.ts的配置
2. 修改src/types/api.ts的类型
3. 更新所有使用该API的组件"
3. 利用工具的併發能力
Claude Code可以並行執行多個獨立的工具呼叫,大幅提升效率。
並行讀取檔案
序列讀取(慢):
Claude: [读取file1.ts]
Claude: [读取file2.ts]
Claude: [读取file3.ts]
时间: 3 + 3 + 3 = 9秒
並行讀取(快):
Claude: [同时读取file1.ts, file2.ts, file3.ts]
时间: max(3, 3, 3) = 3秒
如何觸發並行操作:
你: 分析以下文件的依赖关系:
- src/App.tsx
- src/components/Header.tsx
- src/components/Sidebar.tsx
- src/utils/auth.ts
Claude会在单次响应中并行读取所有文件
並行執行命令
序列執行:
你: 运行测试
[等待测试完成]
你: 运行lint
[等待lint完成]
你: 运行类型检查
[等待类型检查完成]
並行執行:
你: 同时运行以下检查:
1. npm test
2. npm run lint
3. npm run type-check
Claude会并行执行这些命令
實戰示例:批次程式碼審查
## 并行代码审查请求模板
你: 审查以下文件的代码质量:
- src/components/UserCard.tsx
- src/components/UserList.tsx
- src/hooks/useUsers.ts
- src/api/users.ts
检查项:
1. TypeScript类型安全
2. 性能问题(不必要的重渲染)
3. 错误处理
4. 代码规范
Claude会:
1. 并行读取所有4个文件
2. 同时分析每个文件
3. 生成综合报告
时间节省: 从12秒降至4秒
減少等待時間
1. 智慧使用CLAUDE.md
透過CLAUDE.md預設上下文,避免重複解釋:
無CLAUDE.md時:
你: 创建一个API路由
Claude: 好的,什么类型的项目?
你: Node.js + Express
Claude: 使用什么数据库?
你: PostgreSQL + Prisma
Claude: 有编码规范吗?
你: 有的,用TypeScript,严格模式...
[多轮对话后才达成共识]
有CLAUDE.md後:
你: 创建一个用户API路由
Claude: [直接按照CLAUDE.md中的规范创建]
[一次到位,完全符合项目规范]
配置示例:
## Performance Optimization in CLAUDE.md
# Project Setup
## Technology Stack
- Framework: Express + TypeScript
- Database: PostgreSQL + Prisma
- Validation: Zod
- Testing: Jest
## API Route Pattern
When creating API routes:
```typescript
// src/routes/users.ts
import { Router } from 'express';
import { userController } from '@/controllers/userController';
import { validateRequest } from '@/middlewares/validateRequest';
import { userCreateSchema } from '@/validators/userSchemas';
const router = Router();
router.post('/users',
validateRequest(userCreateSchema),
userController.create
);
export { router };
Controller Pattern
// src/controllers/userController.ts
export const userController = {
async create(req: Request, res: Response, next: NextFunction) {
try {
const data = UserCreateSchema.parse(req.body);
const user = await userService.create(data);
res.status(201).json({ success: true, data: user });
} catch (error) {
next(error);
}
}
};
### 2. 使用快捷命令和別名
#### 定義常用操作別名
在CLAUDE.md中定義快捷命令:
```markdown
## Command Aliases
### Testing
When I say "test now", run: `npm run test:watch`
When I say "full test", run: `npm test && npm run test:e2e`
When I say "coverage", run: `npm run test:coverage`
### Development
When I say "dev", run: `npm run dev`
When I say "build dev", run: `npm run build:dev`
When I say "build prod", run: `npm run build:prod`
### Code Quality
When I say "check all", run: `npm run lint && npm run type-check`
When I say "fix code", run: `npm run lint -- --fix && npm run format`
### Git
When I say "quick commit", ask for commit message then:
1. git add .
2. git commit -m "[message]"
3. git push
When I say "status check", run: `git status && git log -1 --stat`
使用效果:
你: check all
Claude: [运行npm run lint和npm run type-check]
节省时间: 不用每次输入完整命令
建立任務模板
## Task Templates
### New Feature Template
When I ask to "create a feature [name]", follow these steps:
1. Ask for feature details if unclear
2. Create feature branch: `git checkout -b feature/[name]`
3. Create necessary files (component, hooks, types, styles)
4. Implement functionality
5. Add tests (min 80% coverage)
6. Run: `npm run check all`
7. Ask if I want to commit changes
### Bug Fix Template
When I ask to "fix bug [description]", follow these steps:
1. Ask for reproduction steps if unclear
2. Create minimal test case
3. Locate and fix the bug
4. Add regression test
5. Verify all tests pass
6. Ask if I want to commit changes
3. 上下文預熱技巧
專案啟動時預熱
## Session Start Warmup
When starting a new session:
1. Quick project scan:
- Read package.json for dependencies
- Read tsconfig.json for TypeScript config
- List project structure (ls -la)
2. Load key files:
- CLAUDE.md
- Main config files
- Recent commits (git log -5)
This takes 5 seconds but saves 30+ seconds per session
實際使用:
你: /warmup
Claude: [执行预设的预热流程]
你: 现在可以快速处理任何请求了
智慧快取策略
## Caching Strategy
### Cache These in Memory
- Project structure (directory tree)
- Package.json dependencies
- Common file locations
- Coding conventions
### Invalidate Cache When
- package.json changes
- Project structure changes
- New dependencies added
上下文最佳化
1. 精簡上下文內容
只包含必要資訊
過度冗餘的CLAUDE.md:
## Project Overview
This project is an e-commerce platform... [500字介绍]
## Technology Stack
We use React because it's... [300字解释]
## Architecture
Our architecture follows... [400字详细说明]
## Coding Conventions
Here are detailed explanations of every rule... [1000字]
总计: 2200字,每次请求都传输
精簡高效的CLAUDE.md:
## Project
E-commerce platform (React + Next.js)
## Tech Stack
- Next.js 14, React 18, TypeScript
- Prisma + PostgreSQL
- Tailwind CSS
## Quick Rules
- Functional components only
- Use Server Components by default
- All functions need return types
- No any types
总计: 50字,信息密度高
效能影響:
- 冗餘版本: 每次請求消耗額外2000 tokens
- 精簡版本: 只消耗50 tokens
- 節省: 97.5%的上下文開銷