跳至主要内容

效能最佳化最佳實踐

用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%的上下文開銷

使用引用而非複製

不好:直接複製文件

## API Documentation

Here is the complete API documentation... [复制整个API文档,5000字]

好:使用引用

## API Documentation
See: `/docs/api.md` or `http://localhost:3000/api-docs`

Key endpoints:
- POST /api/users - Create user
- GET /api/users/:id - Get user
- PUT /api/users/:id - Update user

2. 分層上下文管理

環境特定配置

## Environment-Aware Context

### Development Mode
Additional context loaded:
- Mock data locations
- Debugging tools
- Hot reload config

### Production Mode
Stripped context:
- Only production configs
- Security requirements
- Performance guidelines

### Context Loading Rules
if (NODE_ENV === 'development') {
load('development-rules.md');
load('debugging-tools.md');
} else if (NODE_ENV === 'production') {
load('production-checklist.md');
load('security-requirements.md');
}

動態上下文載入

## Dynamic Context Loading

### Task-Based Context
When working on authentication:
→ Load auth-related configs and rules
→ Exclude UI styling rules

When working on UI components:
→ Load styling guidelines
→ Exclude backend API rules

### Implementation
You can signal context needs:
"Focus on: authentication"
→ Claude loads auth-specific context

"Focus on: UI components"
→ Claude loads styling context

3. 上下文視窗最佳化

Token使用策略

## Token Budget Management

### Budget Allocation (Total: 200K tokens)
- CLAUDE.md: 2,000 tokens (1%)
- Current task context: 10,000 tokens (5%)
- File contents: 50,000 tokens (25%)
- Claude's response: 30,000 tokens (15%)
- Reserved for expansion: 108,000 tokens (54%)

### Optimization Rules
1. CLAUDE.md should be < 3,000 tokens
2. Avoid reading large files (>1000 lines) unless necessary
3. Use grep to search instead of reading entire files
4. Prioritize relevant files over comprehensive scans

### Token-Saving Techniques
❌ "Read all React components"
✅ "Read components related to user authentication"

❌ "Analyze the entire codebase"
✅ "Analyze src/api and src/controllers directories"

大檔案處理策略

## Large File Handling

### For Files > 500 Lines
Instead of:
❌ Read the entire file

Use:
✅ Grep for specific patterns
✅ Read specific sections (with line numbers)
✅ Ask Claude to summarize first

### Example
Instead of:
"Read src/components/Dashboard.tsx" [1200 lines]

Use:
"Search for 'useEffect' in Dashboard.tsx and read surrounding context"
or
"Read lines 1-100 of Dashboard.tsx to understand the structure"
or
"Summarize the Dashboard component's main responsibilities"

併發操作

1. 多工並行處理

並行檔案讀取模式

理論基礎: Claude Code可以在單次響應中並行呼叫多個工具。理解這一點是效能最佳化的關鍵。

示例:跨檔案引用分析

你: 分析AuthService在哪些文件中被使用
Claude:
[并行执行]
- Grep: "AuthService" in src/
- Read: src/services/AuthService.ts
- Read: src/services/index.ts

[综合分析后报告]
Found in 12 files:
- src/components/LoginForm.tsx (imports)
- src/middleware/auth.ts (uses)
...

效能對比:

  • 序列方式: 3 + 3 + 3 = 9秒
  • 並行方式: max(3, 3, 3) = 3秒
  • 節省: 67%時間

批次程式碼生成

## Parallel Code Generation Template

### Scenario: Create CRUD for a Resource
Instead of:
❌ "Create User model"
❌ "Create User controller"
❌ "Create User routes"
❌ "Create User validators"

Use:
✅ "Create complete CRUD for User resource:
1. Prisma schema model
2. Controller with create/read/update/delete
3. Express routes with validation
4. Zod validation schemas
5. TypeScript types
6. Unit tests"

Claude will:
1. Read related files in parallel (schema, existing controllers)
2. Generate all files
3. Ensure consistency across files

Time: One request instead of 6

2. 獨立任務併發

測試+構建並行

你: 准备发布前的完整检查
Claude:
[并行执行]
1. npm test
2. npm run lint
3. npm run type-check
4. npm run build
5. git status

[汇总所有结果]

為什麼更快?

  • 這些任務相互獨立
  • 並行執行 = 總時間 = max(各任務時間)
  • 序列執行 = 總時間 = sum(各任務時間)

實際時間對比:

串行: 30s + 15s + 20s + 45s + 2s = 112秒
并行: max(30s, 15s, 20s, 45s, 2s) = 45秒
节省: 60%

程式碼審查+文件生成

## Concurrent Review and Documentation

Request:
"Review src/api/users.ts and generate usage documentation"

Claude will:
1. Read the API file
2. Analyze code quality
3. Find usage examples in codebase
4. Generate README documentation

All done in parallel where possible

3. 流水線最佳化

智慧任務依賴管理

## Pipeline Optimization

### Independent Tasks → Parallel
✅ Run tests + Lint + Type-check (no dependencies)
✅ Read multiple files (no dependencies)
✅ Search multiple patterns (no dependencies)

### Dependent Tasks → Sequential
⚠️ Build then Test (need build artifacts)
⚠️ Migrate then Seed (need schema changes)
⚠️ Generate then Commit (need files created)

### Mixed Pipeline
Example workflow:
1. Parallel: Read all config files
2. Sequential: Analyze dependencies (needs config)
3. Parallel: Generate all components
4. Sequential: Create index.ts (needs components)
5. Parallel: Run tests + lint
6. Sequential: Commit (needs all changes)

Optimized: 45s vs Sequential: 90s

實戰:完整功能開發流水線

## Complete Feature Pipeline

### Request
"Create user profile feature with:
- Profile viewing
- Profile editing
- Avatar upload
- Include tests and documentation"

### Optimized Execution
Phase 1 (Parallel):
- Read existing user routes
- Read upload configuration
- Read database schema

Phase 2 (Sequential):
- Design API endpoints
- Plan component structure

Phase 3 (Parallel):
- Create API routes
- Create React components
- Create validation schemas

Phase 4 (Parallel):
- Write API tests
- Write component tests

Phase 5 (Parallel):
- Generate documentation
- Run full test suite

### Time Breakdown
Phase 1: 3s (parallel reads)
Phase 2: 5s (planning)
Phase 3: 12s (parallel generation)
Phase 4: 15s (parallel testing)
Phase 5: 8s (docs + tests)
Total: 43s

### Sequential Alternative
3 + 5 + 12 + 15 + 8 + (overhead) = 60s+

Savings: 28%

快取利用

1. 檔案系統快取

理解快取機制

Claude Code會快取讀取的檔案內容,避免重複讀取:

第一次讀取:

你: 读取package.json
Claude: [从磁盘读取,耗时1秒]

後續讀取:

你: 再次读取package.json
Claude: [从缓存读取,几乎瞬时]

利用快取的策略

## Cache Utilization Strategy

### Batch File Reads
❌ Bad: Spread reads across multiple requests
Request 1: "Read file A"
Request 2: "Read file B"
Request 3: "Read file C"

✅ Good: Read all files in one request
Request 1: "Read files A, B, and C"

Benefit:
- All files cached in one operation
- Subsequent requests use cache
- Faster overall

### Working Set Strategy
Identify your "working set" - files you frequently work with

Example: Frontend Developer
Working Set:
- src/components/ (all components)
- src/hooks/ (custom hooks)
- src/types/ (type definitions)

Strategy: Read entire working set once at start of session
"Read all TypeScript files in src/components and src/hooks"
→ All files cached
→ Subsequent operations are instant

2. 模式匹配快取

智慧搜尋策略

## Pattern Matching Cache

### Grep Results Are Cached
First search:
"Grep for 'useState' in src/components/"
→ Scans all files, results cached

Second search:
"Grep for 'useState' in src/components/"
→ Returns cached results instantly

### Strategy: Broad Searches First
❌ Bad: Narrow searches, then broad
"Grep for 'useState' in components/Button.tsx"
"Grep for 'useState' in components/Input.tsx"
"Grep for 'useState' in components/Form.tsx"

✅ Good: Broad search once
"Grep for 'useState' in src/components/"
→ Results cached
→ Filter mentally or ask Claude to filter

### Example Workflow
You: "Find all components using Redux"
Claude: [Grep entire src/, results cached]

You: "Which of these use useSelector?"
Claude: [Filters cached results]
→ Instant response, no re-scan

3. 專案級快取策略

初始化快取

## Session Initialization

### Warmup Strategy
Start each session with cache warmup:

"Warmup: Read and cache these directories:
1. src/config/ - all configuration files
2. src/types/ - all type definitions
3. CLAUDE.md - project context
4. package.json - dependencies"

Time: 5 seconds
Benefit: All subsequent operations are faster

### Progressive Loading
Don't load everything at once

Phase 1 (Session Start):
- Load project structure
- Load CLAUDE.md
- Load config files

Phase 2 (When Needed):
- Load component files (when working on UI)
- Load API files (when working on backend)

Benefit:
- Fast session start
- Still cache relevant files
- Avoid unnecessary loading

快取失效處理

## Cache Invalidation

### Automatic Invalidation
Claude automatically invalidates cache when:
- Files are modified (via Edit tool)
- New files are created
- Files are deleted

### Manual Refresh
If you modify files outside Claude:
"Refresh: package.json has been updated"
→ Claude reloads file
→ Cache updated

### Working with External Tools
When using other editors (VS Code, etc.):

Before asking Claude to analyze:
1. Save changes in external editor
2. Tell Claude: "I've updated X file externally, please reload"
3. Claude refreshes cache
4. Proceed with analysis

4. 會話狀態快取

對話歷史利用

## Conversation Context Caching

### Claude Remembers Within Session
First occurrence:
You: "We use TypeScript strict mode"
Claude: [Noted for this session]

Later in same session:
You: "Create a new component"
Claude: [Creates with strict mode compliance]
→ No need to repeat instructions

### Establish Patterns Early
At start of session:
"Session setup:
- We're working on authentication feature
- Focus on security and error handling
- Use TypeScript strict mode
- All functions need return types"

Benefit: Subsequent requests follow these patterns automatically

### Reset When Needed
If switching contexts:
"Reset: Now working on UI styling, different from auth feature"
→ Claude adjusts expectations
→ Previous patterns don't interfere

效能監控

1. 響應時間追蹤

建立效能基線

## Performance Baseline

### Measure Your Operations
Track these metrics:

1. File Read Operations
- Small file (<100 lines): should be <2s
- Medium file (100-500 lines): should be <3s
- Large file (>500 lines): should be <5s

2. Code Generation
- Simple component: <5s
- Complex feature: <15s
- Multi-file refactor: <30s

3. Analysis Tasks
- Single file analysis: <5s
- Multi-file analysis: <10s
- Codebase search: <8s

### Tracking Template
Maintain a performance log:

| Operation | Expected | Actual | Notes |
|-----------|----------|--------|-------|
| Read component | 2s | 1.5s | ✓ Good |
| Generate feature | 15s | 25s | ✗ Slow, investigate |
| Search codebase | 8s | 20s | ✗ Large project, narrow scope |

識別效能瓶頸

## Bottleneck Identification

### Common Bottlenecks

1. **Excessive Context**
Symptom: Requests take >10s for simple tasks
Cause: CLAUDE.md too large or reading unnecessary files
Solution: Simplify CLAUDE.md, be specific about files to read

2. **Vague Requests**
Symptom: Claude asks many clarifying questions
Cause: Request lacks specificity
Solution: Provide detailed requirements upfront

3. **Large File Scans**
Symptom: Reading large files takes >10s
Cause: Reading entire file when only need part
Solution: Use grep or specify line ranges

4. **Sequential Operations**
Symptom: Total time is sum of all operations
Cause: Not leveraging parallel execution
Solution: Combine related requests

### Diagnosis Checklist
If performance is slow:
- [ ] Is CLAUDE.md concise (<2000 tokens)?
- [ ] Are requests specific and detailed?
- [ ] Am I reading only necessary files?
- [ ] Can operations be done in parallel?
- [ ] Am I repeating information Claude already knows?

2. Token使用監控

追蹤Token消耗

## Token Usage Tracking

### Why Monitor Tokens?
- Cost efficiency (API calls are paid)
- Context window limits
- Performance indicator

### Token Budget by Task Type

1. **Simple Questions** (<500 tokens)
- "What does this function do?"
- "How do I use this component?"

2. **Code Analysis** (500-2000 tokens)
- "Review this file for bugs"
- "Explain this code structure"

3. **Code Generation** (2000-5000 tokens)
- "Create a new feature"
- "Refactor this component"

4. **Large Refactors** (5000-10000 tokens)
- "Update entire codebase to new pattern"
- "Migrate to new framework"

### Monitoring Strategy
After each complex operation:
"Show me token usage for last operation"
→ Claude reports tokens used
→ Track patterns over time

### Optimization Targets
- Simple tasks: <1000 tokens
- Medium tasks: <3000 tokens
- Complex tasks: <8000 tokens
- If consistently over: Optimize CLAUDE.md or request structure

Token最佳化技術

## Token Optimization Techniques

### 1. Precise File Selection
❌ "Read all components in src/components/"
(10 files × 500 tokens = 5000 tokens)

✅ "Read UserCard and UserList components"
(2 files × 500 tokens = 1000 tokens)
Savings: 80%

### 2. Grep Over Read
❌ "Find all API calls" [Reads entire codebase]
(50,000+ tokens)

✅ "Grep for 'fetch(' in src/"
(~500 tokens for results)
Savings: 99%

### 3. Incremental Context
❌ Repeat entire project context every request
(2000 tokens per request)

✅ Reference established context
"I'm still working on the auth feature we discussed"
(~100 tokens)
Savings: 95%

### 4. Focused Requests
❌ "Analyze everything about this component"
(6000 tokens for deep analysis)

✅ "Check for TypeScript errors in this component"
(1000 tokens for focused analysis)
Savings: 83%

3. 效率指標

定義成功指標

## Efficiency Metrics

### Key Performance Indicators (KPIs)

1. **First-Time Success Rate**
Target: >80%
Meaning: Percentage of tasks completed correctly on first try
How to improve: Better CLAUDE.md, more specific requests

2. **Average Response Time**
Target: <5s for simple tasks
Target: <15s for medium tasks
How to improve: Optimize context, use parallel operations

3. **Token Efficiency**
Target: <2000 tokens per simple task
Target: <5000 tokens per complex task
How to improve: Precise file selection, focused requests

4. **Rework Rate**
Target: <20%
Meaning: Percentage of tasks requiring revision
How to improve: Clear requirements, better examples

### Measuring Success
Weekly review:
- This week I completed 50 tasks with Claude
- First-time success: 42/50 (84%) ✓
- Avg response time: 4.2s ✓
- Avg tokens per task: 1800 ✓
- Rework needed: 8/50 (16%) ✓
Overall: Excellent performance

持續改進

## Continuous Improvement

### Performance Review Template

#### Weekly Review
**Tasks Completed:** [number]
**Avg Response Time:** [time]
**First-Time Success:** [percentage]
**Common Bottlenecks:**
1. [bottleneck 1]
2. [bottleneck 2]

**Improvement Actions:**
- [ ] Action to address bottleneck 1
- [ ] Action to address bottleneck 2

#### Monthly Review
**Trends:**
- Response time: Improving/Stable/Worsening
- Token usage: Decreasing/Stable/Increasing
- Success rate: Improving/Stable/Worsening

**Actions Taken:**
- [x] Updated CLAUDE.md (date)
- [x] Optimized request patterns (date)
- [x] Added command aliases (date)

**Next Month's Focus:**
1. [Priority 1]
2. [Priority 2]

實用技巧和最佳實踐

1. 請求最佳化清單

傳送請求前的檢查

## Pre-Request Checklist

Before sending a request to Claude:

### Context Preparation
- [ ] Have I established the context? (Is this a new topic?)
- [ ] Is the context in CLAUDE.md or should I provide it?
- [ ] Can I reference previous work instead of repeating?

### Request Clarity
- [ ] Is my request specific and detailed?
- [ ] Have I provided examples of expected output?
- [ ] Have I specified constraints (files to include/exclude)?

### Optimization Opportunities
- [ ] Can I combine multiple related requests?
- [ ] Can operations be done in parallel?
- [ ] Am I reading only necessary files?

### Token Efficiency
- [ ] Is CLAUDE.md concise and relevant?
- [ ] Am I avoiding redundant information?
- [ ] Can I use grep instead of reading large files?

### Quality Assurance
- [ ] Have I specified the expected format?
- [ ] Have I mentioned relevant coding standards?
- [ ] Have I provided necessary file paths?

### Expected Results
After checking all items:
- Faster responses (30-50% improvement)
- Higher first-time success rate (80%+)
- Lower token usage (40-60% reduction)

請求模板庫

## Request Templates

### Template 1: Code Generation

Create [feature/component/function] with these requirements:

Purpose: [What it should do] Location: [File path] Tech Stack: [Relevant technologies] Specifications:

  1. [Requirement 1]
  2. [Requirement 2]
  3. [Requirement 3]

Constraints:

  • [Constraint 1]
  • [Constraint 2]

Expected Output:

  • [Output format/structure]

Follow project coding conventions in CLAUDE.md.


### Template 2: Bug Investigation

Investigate this issue: Symptom: [What's happening] Expected: [What should happen] Location: [Where it occurs] Steps to Reproduce:

  1. [Step 1]
  2. [Step 2]
  3. [Step 3]

Context:

  • Related files: [list]
  • Recent changes: [description]

Please:

  1. Identify the root cause
  2. Propose a fix
  3. Suggest regression tests

### Template 3: Refactoring

Refactor [component/module]: Current Issues:

  • [Issue 1]
  • [Issue 2]

Goals:

  • [Goal 1]
  • [Goal 2]

Files to Modify:

  • [File 1]
  • [File 2]

Constraints:

  • Maintain backward compatibility
  • Don't break existing tests
  • Follow project conventions

Please analyze, plan, and implement the refactoring.


### Template 4: Code Review

Review [file/component] for:

  1. TypeScript type safety
  2. Performance issues
  3. Security vulnerabilities
  4. Code convention compliance
  5. Error handling

Context:

  • Purpose: [What it does]
  • Dependencies: [What it uses]

Please provide:

  • List of issues found
  • Severity levels (Critical/High/Medium/Low)
  • Specific recommendations
  • Code examples for fixes

2. 高階工作流

迭代開發模式

## Iterative Development Workflow

### Phase 1: Planning (Quick)
You: "Help me plan user authentication feature:
- Login with email/password
- JWT tokens
- Password reset
- Session management"

Claude: [Analyzes requirements, creates task list]
→ Output: Structured plan with steps
→ Time: 10-15s

### Phase 2: Implementation (Parallel)
You: "Implement Phase 1: Login endpoint:
1. POST /api/auth/login
2. Validate email/password with Zod
3. Generate JWT
4. Return token + user info
Create:
- src/routes/auth.ts
- src/controllers/authController.ts
- src/validators/authSchemas.ts
- src/types/auth.ts"

Claude: [Creates all files in parallel]
→ Time: 15-20s

### Phase 3: Testing (Automated)
You: "Create tests for login endpoint:
- Unit tests for controller
- Integration tests for API
- Cover success and error cases"

Claude: [Generates comprehensive tests]
→ Time: 10-15s

### Phase 4: Verification (Quick)
You: "Run all tests and linting"
Claude: [Parallel execution]
→ Time: 5-10s

### Total Time: 40-60s for complete feature
### Traditional approach: 5-10 minutes
### Speed improvement: 5-10x

除錯工作流

## Debugging Workflow

### Step 1: Isolate (2s)
You: "I have an error in user login. Error: 'Invalid credentials'
But I'm sure the password is correct.
Location: src/controllers/authController.ts line 25"

Claude: [Reads specific file and location]
→ Immediate context loaded

### Step 2: Reproduce (5s)
You: "Show me the login flow and where it might fail"

Claude: [Analyzes the flow]
→ Points out:
- Password comparison logic
- Database query
- Error handling

### Step 3: Diagnose (3s)
You: "Check if password hashing is correct"

Claude: [Grep for password-related code]
→ Finds: Registration uses bcrypt(10)
→ Finds: Login uses bcrypt.compare()
→ Discovers: Comparison is async but not awaited

### Step 4: Fix (2s)
You: "Fix the issue"

Claude: [Adds await to bcrypt.compare()]
→ Fixed

### Step 5: Test (5s)
You: "Add regression test for this bug"

Claude: [Creates test case]
→ Prevents future recurrence

### Total Time: 17s
### Manual debugging: 5-15 minutes
### Speed improvement: 20-50x

3. 團隊協作最佳化

共享效能實踐

## Team Performance Optimization

### Shared CLAUDE.md Configuration

Create a team-standard CLAUDE.md template:

```markdown
# Team CLAUDE.md Standard

## Required Sections
1. Project Overview (max 100 words)
2. Technology Stack (list only)
3. Quick Rules (bullet points, 10 items max)
4. Common Commands (grouped by purpose)
5. File Structure (key directories only)

## Token Budget
- CLAUDE.md max: 2000 tokens
- Aim for 1000-1500 tokens typically

## Review Process
- Tech Lead reviews CLAUDE.md changes
- Update frequency: Monthly or after major changes
- Team vote on significant additions

Performance Standards

Establish team performance baselines:

File Operations:

  • Single file read: under 2s
  • Multi-file read (3-5 files): under 5s
  • Grep search: under 3s

Code Generation:

  • Simple component: under 5s
  • Complex feature: under 20s
  • Multi-file refactor: under 30s

Quality Targets:

  • First-time success: >80%
  • TypeScript errors: under 5% of generated code
  • Lint errors: under 5% of generated code

Team Training

Onboard new members with performance focus:

Week 1: Basics

  • How to write effective requests
  • CLAUDE.md overview
  • Common command aliases

Week 2: Optimization

  • Token efficiency
  • Parallel operations
  • Request templates

Week 3: Advanced

  • Complex workflows
  • Debugging strategies
  • Performance monitoring

Ongoing:

  • Monthly performance reviews
  • Share optimization tips
  • Maintain team request library

#### 知識共享

```markdown
## Knowledge Sharing System

### Request Library

Maintain a library of proven effective requests:

```markdown
## Team Request Library

### Authentication
Login endpoint creation:
[Copy proven request template]

Password reset flow:
[Copy proven request template]

### Frontend Components
Form component with validation:
[Copy proven request template]

Data table with sorting:
[Copy proven request template]

### Backend APIs
CRUD API generation:
[Copy proven request template]

Error handling middleware:
[Copy proven request template]

Performance Tips Log

Team members contribute tips:

From Sarah: "Use 'Focus on X' to limit context scope. Improved my response time by 40%."

From Mike: "Batch file reads at start of session. Saved me 10+ minutes per day."

From Lisa: "Always include expected output format. Reduced rework from 30% to 10%."

Monthly Performance Sharing

Team meeting agenda:

  1. Performance metrics review
  2. Success stories share
  3. New techniques demo
  4. Q&A and troubleshooting

### 4. 故障排除

#### 常見效能問題

```markdown
## Troubleshooting Performance Issues

### Problem 1: Slow Responses

**Symptoms:**
- Simple requests taking >10 seconds
- Claude seems "stuck" or "thinking" too long
- Intermittent slowness

**Diagnosis:**
1. Check CLAUDE.md size (target: <2000 tokens)
2. Review request clarity
3. Check if reading unnecessary files
4. Verify internet connection

**Solutions:**
- Trim CLAUDE.md to essentials
- Be more specific in requests
- Use grep instead of reading large files
- Combine related requests

### Problem 2: High Token Usage

**Symptoms:**
- Reaching context limits quickly
- High API costs
- Requests being truncated

**Diagnosis:**
1. Track token usage per request
2. Identify patterns of high usage
3. Check for redundant information

**Solutions:**
- Reduce CLAUDE.md size
- Read only necessary files
- Use grep for searching
- Reference established context
- Be selective about code examples

### Problem 3: Low First-Time Success

**Symptoms:**
- Frequent need for revisions
- Claude misunderstands requirements
- Generated code doesn't match expectations

**Diagnosis:**
1. Review request clarity
2. Check if context is complete
3. Verify expectations are communicated

**Solutions:**
- Provide detailed requirements upfront
- Include examples of expected output
- Specify constraints explicitly
- Reference CLAUDE.md conventions
- Use request templates

### Problem 4: Repetitive Explanations

**Symptoms:**
- Repeating same information across requests
- Claude forgetting context
- Inconsistent responses

**Diagnosis:**
1. Check if information is in CLAUDE.md
2. Review session context usage
3. Verify cache is being utilized

**Solutions:**
- Add recurring info to CLAUDE.md
- Reference previous discussions
- Use command aliases
- Establish session context early

效能恢復策略

## Performance Recovery

### When Performance Degrades

**Immediate Actions:**
1. Clear the air: "Let me reset context. We're working on [X]"
2. Simplify CLAUDE.md (temporarily)
3. Use more focused requests
4. Break large tasks into smaller ones

**Session Reset:**

"Session reset:

  • Clear previous context
  • Current focus: [specific task]
  • Relevant files: [list only what's needed]
  • Constraints: [key constraints only]"

**Starting Fresh:**
If performance is consistently poor:
1. End current session
2. Review and optimize CLAUDE.md
3. Start new session with clean context
4. Re-establish working set gradually

### Prevention Strategies

**Daily Practices:**
- Start session with context warmup
- Use request templates
- Monitor token usage
- Take breaks for long sessions

**Weekly Practices:**
- Review CLAUDE.md for bloat
- Clean up request templates
- Update performance metrics
- Share learnings with team

**Monthly Practices:**
- Major CLAUDE.md revision
- Performance baseline review
- Process optimization
- Team training updates

總結與行動指南

核心原則回顧

效能最佳化的五個核心原則:

  1. 精確性優先

    • 明確的請求 > 模糊的請求
    • 具體的檔案範圍 > 廣泛的掃描
    • 清晰的約束 > 開放的問題
  2. 並行思維

    • 識別獨立操作
    • 批次檔案讀取
    • 並行任務執行
  3. 上下文管理

    • 精簡CLAUDE.md
    • 智慧快取利用
    • 分層上下文載入
  4. 持續監控

    • 追蹤響應時間
    • 監控token使用
    • 測量成功率
  5. 迭代改進

    • 建立效能基線
    • 識別瓶頸
    • 逐步最佳化

立即可行的最佳化

今天就可以做的(5分鐘)

## Quick Wins (5 Minutes)

### 1. Trim CLAUDE.md
- Remove redundant explanations
- Use bullet points instead of paragraphs
- Keep only essential information
→ Expected: 30-50% token reduction

### 2. Create Request Template
Copy this template and save it:

Create [what] with these specs:

  • Purpose: [why]
  • Location: [where]
  • Tech: [stack]
  • Requirements: [list]
  • Constraints: [limits]
→ Expected: 40% faster request formulation

### 3. Set Up Performance Tracking
Create a simple log:

Date | Task | Time | Tokens | Success?

→ Expected: Identify improvement areas

### 4. Learn Command Aliases
Add to CLAUDE.md:

When I say "test", run: npm test When I say "check", run: npm run lint && npm run type-check

→ Expected: Save 10+ seconds per command

本週可以做的(30分鐘)

## This Week (30 Minutes)

### Monday: CLAUDE.md Optimization (10 min)
- Review entire CLAUDE.md
- Remove outdated information
- Consolidate redundant sections
- Add missing critical info
- Measure token count (target: <2000)

### Tuesday: Request Patterns (10 min)
- Identify your 3 most common request types
- Create templates for each
- Test templates with actual tasks
- Refine based on results

### Wednesday: Batch Operations (10 min)
- Identify tasks you do sequentially
- Plan how to combine them
- Test parallel execution
- Measure time saved

### Thursday: Cache Strategy (10 min)
- Identify your working set files
- Create warmup routine
- Test cache effectiveness
- Adjust as needed

### Friday: Performance Review (10 min)
- Review week's performance log
- Identify top 3 bottlenecks
- Plan fixes for next week
- Celebrate improvements!

持續改進計劃

## Continuous Improvement Plan

### Month 1: Foundation
**Goal:** Establish performance baselines

Week 1:
- Optimize CLAUDE.md
- Create request templates
- Set up tracking

Week 2:
- Learn parallel operations
- Implement batch workflows
- Measure improvements

Week 3:
- Optimize caching strategy
- Create command aliases
- Share with team

Week 4:
- Review metrics
- Identify patterns
- Plan Month 2

**Expected Results:**
- 40% faster responses
- 60% less token usage
- 80% first-time success rate

### Month 2: Advanced
**Goal:** Master advanced techniques

Focus areas:
- Complex workflow optimization
- Team collaboration
- Performance monitoring
- Advanced troubleshooting

### Month 3: Mastery
**Goal:** Team-wide optimization

Focus areas:
- Knowledge sharing
- Process documentation
- Team training
- Continuous optimization culture

效能目標清單

使用此清單跟蹤你的最佳化進度:

## Performance Optimization Checklist

### CLAUDE.md Optimization
- [ ] Size < 2000 tokens
- [ ] Contains all critical info
- [ ] No redundant content
- [ ] Clear and concise
- [ ] Team-reviewed (if applicable)

### Request Quality
- [ ] Always provide clear requirements
- [ ] Specify expected output format
- [ ] Mention relevant constraints
- [ ] Include file paths when applicable
- [ ] Use request templates

### Parallel Operations
- [ ] Batch file reads
- [ ] Combine related requests
- [ ] Execute independent tasks in parallel
- [ ] Use concurrent tool calls
- [ ] Optimize task dependencies

### Context Management
- [ ] Working set identified
- [ ] Cache warmed up at session start
- [ ] Context refreshed when needed
- [ ] Unnecessary context excluded
- [ ] Session reset when switching topics

### Performance Monitoring
- [ ] Response time tracked
- [ ] Token usage monitored
- [ ] Success rate measured
- [ ] Bottlenecks identified
- [ ] Improvements documented

### Continuous Improvement
- [ ] Weekly performance reviews
- [ ] Monthly CLAUDE.md updates
- [ ] Regular optimization of workflows
- [ ] Team knowledge sharing
- [ ] Staying updated with best practices

最終建議

記住這些關鍵點:

  1. 最佳化是漸進的 - 不要試圖一次最佳化所有東西
  2. 測量是關鍵 - 無法測量的東西就無法改進
  3. 模式很重要 - 識別並重用高效的工作模式
  4. 共享倍增價值 - 與團隊分享你的發現
  5. 持續迭代 - 效能最佳化永遠在路上

立即行動:

  • 選擇一個最佳化領域開始
  • 測量當前效能
  • 實施改進
  • 測量結果
  • 迭代改進

最終目標: 讓Claude Code成為你最高效的程式設計夥伴,而不是最昂貴的聊天工具。

參考資源

官方文件

社羣資源

相關文章


下一步行動:

  1. 審查你當前的CLAUDE.md並最佳化
  2. 選擇一個工作流程進行最佳化
  3. 建立效能追蹤機制
  4. 與團隊分享這些最佳實踐