optimizing-performance

Compare original and translation side by side

🇺🇸

Original

English
🇨🇳

Translation

Chinese

Optimizing Performance

性能优化

Performance Optimization Workflow

性能优化工作流

Copy this checklist and track progress:
Performance Optimization Progress:
- [ ] Step 1: Measure baseline performance
- [ ] Step 2: Identify bottlenecks
- [ ] Step 3: Apply targeted optimizations
- [ ] Step 4: Measure again and compare
- [ ] Step 5: Repeat if targets not met
Critical Rule: Never optimize without data. Always profile before and after changes.
复制此清单并跟踪进度:
Performance Optimization Progress:
- [ ] Step 1: Measure baseline performance
- [ ] Step 2: Identify bottlenecks
- [ ] Step 3: Apply targeted optimizations
- [ ] Step 4: Measure again and compare
- [ ] Step 5: Repeat if targets not met
重要规则:永远不要在没有数据支撑的情况下进行优化。在修改前后都必须进行性能分析。

Step 1: Measure Baseline

步骤1:测量基准性能

Profiling Commands

性能分析命令

bash
undefined
bash
undefined

Node.js profiling

Node.js profiling

node --prof app.js node --prof-process isolate*.log > profile.txt
node --prof app.js node --prof-process isolate*.log > profile.txt

Python profiling

Python profiling

python -m cProfile -o profile.stats app.py python -m pstats profile.stats
python -m cProfile -o profile.stats app.py python -m pstats profile.stats

Web performance

Web performance

lighthouse https://example.com --output=json
undefined
lighthouse https://example.com --output=json
undefined

Step 2: Identify Bottlenecks

步骤2:识别瓶颈

Common Bottleneck Categories

常见瓶颈类别

CategorySymptomsTools
CPUHigh CPU usage, slow computationProfiler, flame graphs
MemoryHigh RAM, GC pauses, OOMHeap snapshots, memory profiler
I/OSlow disk/network, waitingstrace, network inspector
DatabaseSlow queries, lock contentionQuery analyzer, EXPLAIN
类别症状工具
CPU高CPU使用率、计算缓慢性能分析器、火焰图
内存高内存占用、GC停顿、内存不足(OOM)堆快照、内存分析器
I/O磁盘/网络缓慢、等待时间长strace、网络检查器
数据库查询缓慢、锁竞争查询分析器、EXPLAIN

Step 3: Apply Optimizations

步骤3:实施优化

Frontend Optimizations

前端优化

Bundle Size:
javascript
// ❌ Import entire library
import _ from 'lodash';

// ✅ Import only needed functions
import debounce from 'lodash/debounce';

// ✅ Use dynamic imports for code splitting
const HeavyComponent = lazy(() => import('./HeavyComponent'));
Rendering:
javascript
// ❌ Render on every parent update
function Child({ data }) {
  return <ExpensiveComponent data={data} />;
}

// ✅ Memoize when props don't change
const Child = memo(function Child({ data }) {
  return <ExpensiveComponent data={data} />;
});

// ✅ Use useMemo for expensive computations
const processed = useMemo(() => expensiveCalc(data), [data]);
Images:
html
<!-- ❌ Unoptimized -->
<img src="large-image.jpg" />

<!-- ✅ Optimized -->
<img
  src="image.webp"
  srcset="image-300.webp 300w, image-600.webp 600w"
  sizes="(max-width: 600px) 300px, 600px"
  loading="lazy"
  decoding="async"
/>
包体积优化:
javascript
// ❌ Import entire library
import _ from 'lodash';

// ✅ Import only needed functions
import debounce from 'lodash/debounce';

// ✅ Use dynamic imports for code splitting
const HeavyComponent = lazy(() => import('./HeavyComponent'));
渲染优化:
javascript
// ❌ Render on every parent update
function Child({ data }) {
  return <ExpensiveComponent data={data} />;
}

// ✅ Memoize when props don't change
const Child = memo(function Child({ data }) {
  return <ExpensiveComponent data={data} />;
});

// ✅ Use useMemo for expensive computations
const processed = useMemo(() => expensiveCalc(data), [data]);
图片优化:
html
<!-- ❌ Unoptimized -->
<img src="large-image.jpg" />

<!-- ✅ Optimized -->
<img
  src="image.webp"
  srcset="image-300.webp 300w, image-600.webp 600w"
  sizes="(max-width: 600px) 300px, 600px"
  loading="lazy"
  decoding="async"
/>

Backend Optimizations

后端优化

Database Queries:
sql
-- ❌ N+1 Query Problem
SELECT * FROM users;
-- Then for each user:
SELECT * FROM orders WHERE user_id = ?;

-- ✅ Single query with JOIN
SELECT u.*, o.*
FROM users u
LEFT JOIN orders o ON u.id = o.user_id;

-- ✅ Or use pagination
SELECT * FROM users LIMIT 100 OFFSET 0;
Caching Strategy:
javascript
// Multi-layer caching
const getUser = async (id) => {
  // L1: In-memory cache (fastest)
  let user = memoryCache.get(`user:${id}`);
  if (user) return user;

  // L2: Redis cache (fast)
  user = await redis.get(`user:${id}`);
  if (user) {
    memoryCache.set(`user:${id}`, user, 60);
    return JSON.parse(user);
  }

  // L3: Database (slow)
  user = await db.users.findById(id);
  await redis.setex(`user:${id}`, 3600, JSON.stringify(user));
  memoryCache.set(`user:${id}`, user, 60);

  return user;
};
Async Processing:
javascript
// ❌ Blocking operation
app.post('/upload', async (req, res) => {
  await processVideo(req.file);  // Takes 5 minutes
  res.send('Done');
});

// ✅ Queue for background processing
app.post('/upload', async (req, res) => {
  const jobId = await queue.add('processVideo', { file: req.file });
  res.send({ jobId, status: 'processing' });
});
数据库查询优化:
sql
-- ❌ N+1 Query Problem
SELECT * FROM users;
-- Then for each user:
SELECT * FROM orders WHERE user_id = ?;

-- ✅ Single query with JOIN
SELECT u.*, o.*
FROM users u
LEFT JOIN orders o ON u.id = o.user_id;

-- ✅ Or use pagination
SELECT * FROM users LIMIT 100 OFFSET 0;
缓存策略:
javascript
// Multi-layer caching
const getUser = async (id) => {
  // L1: In-memory cache (fastest)
  let user = memoryCache.get(`user:${id}`);
  if (user) return user;

  // L2: Redis cache (fast)
  user = await redis.get(`user:${id}`);
  if (user) {
    memoryCache.set(`user:${id}`, user, 60);
    return JSON.parse(user);
  }

  // L3: Database (slow)
  user = await db.users.findById(id);
  await redis.setex(`user:${id}`, 3600, JSON.stringify(user));
  memoryCache.set(`user:${id}`, user, 60);

  return user;
};
异步处理:
javascript
// ❌ Blocking operation
app.post('/upload', async (req, res) => {
  await processVideo(req.file);  // Takes 5 minutes
  res.send('Done');
});

// ✅ Queue for background processing
app.post('/upload', async (req, res) => {
  const jobId = await queue.add('processVideo', { file: req.file });
  res.send({ jobId, status: 'processing' });
});

Algorithm Optimizations

算法优化

javascript
// ❌ O(n²) - nested loops
function findDuplicates(arr) {
  const duplicates = [];
  for (let i = 0; i < arr.length; i++) {
    for (let j = i + 1; j < arr.length; j++) {
      if (arr[i] === arr[j]) duplicates.push(arr[i]);
    }
  }
  return duplicates;
}

// ✅ O(n) - hash map
function findDuplicates(arr) {
  const seen = new Set();
  const duplicates = new Set();
  for (const item of arr) {
    if (seen.has(item)) duplicates.add(item);
    seen.add(item);
  }
  return [...duplicates];
}
javascript
// ❌ O(n²) - nested loops
function findDuplicates(arr) {
  const duplicates = [];
  for (let i = 0; i < arr.length; i++) {
    for (let j = i + 1; j < arr.length; j++) {
      if (arr[i] === arr[j]) duplicates.push(arr[i]);
    }
  }
  return duplicates;
}

// ✅ O(n) - hash map
function findDuplicates(arr) {
  const seen = new Set();
  const duplicates = new Set();
  for (const item of arr) {
    if (seen.has(item)) duplicates.add(item);
    seen.add(item);
  }
  return [...duplicates];
}

Step 4: Measure Again

步骤4:再次测量

After applying optimizations, re-run profiling and compare:
Comparison Checklist:
- [ ] Run same profiling tools as baseline
- [ ] Compare metrics before vs after
- [ ] Verify no regressions in other areas
- [ ] Document improvement percentages
实施优化后,重新运行性能分析并进行对比:
Comparison Checklist:
- [ ] Run same profiling tools as baseline
- [ ] Compare metrics before vs after
- [ ] Verify no regressions in other areas
- [ ] Document improvement percentages

Performance Targets

性能目标

Web Vitals

Web Vitals指标

MetricGoodNeeds WorkPoor
LCP< 2.5s2.5-4s> 4s
FID< 100ms100-300ms> 300ms
CLS< 0.10.1-0.25> 0.25
TTFB< 800ms800ms-1.8s> 1.8s
指标良好待改进较差
LCP< 2.5s2.5-4s> 4s
FID< 100ms100-300ms> 300ms
CLS< 0.10.1-0.25> 0.25
TTFB< 800ms800ms-1.8s> 1.8s

API Performance

API性能指标

MetricTarget
P50 Latency< 100ms
P95 Latency< 500ms
P99 Latency< 1s
Error Rate< 0.1%
指标目标
P50延迟< 100ms
P95延迟< 500ms
P99延迟< 1s
错误率< 0.1%

Validation

验证

After optimization, validate results:
Performance Validation:
- [ ] Metrics improved from baseline
- [ ] No functionality regressions
- [ ] No new errors introduced
- [ ] Changes are sustainable (not one-time fixes)
- [ ] Performance gains documented
If targets not met, return to Step 2 and identify remaining bottlenecks.
优化完成后,验证结果:
Performance Validation:
- [ ] Metrics improved from baseline
- [ ] No functionality regressions
- [ ] No new errors introduced
- [ ] Changes are sustainable (not one-time fixes)
- [ ] Performance gains documented
若未达成目标,返回步骤2识别剩余瓶颈。