performance-profiler

Compare original and translation side by side

🇺🇸

Original

English
🇨🇳

Translation

Chinese

Performance Profiler

性能分析器

Instructions

操作指南

When profiling performance:
  1. Identify the bottleneck type: Network, rendering, memory, or compute
  2. Measure baseline before optimizing
  3. Profile with appropriate tools
  4. Apply optimizations
  5. Measure improvement
进行性能分析时:
  1. 确定瓶颈类型:网络、渲染、内存或计算
  2. 优化前先测量基准性能
  3. 使用合适的工具进行分析
  4. 应用优化方案
  5. 测量优化效果

Web Performance

Web性能优化

Core Web Vitals

核心Web指标

bash
undefined
bash
undefined

Lighthouse CLI

Lighthouse CLI

npx lighthouse https://yoursite.com --view
npx lighthouse https://yoursite.com --view

With specific metrics

仅测量特定指标

npx lighthouse https://yoursite.com --only-categories=performance

**Target Metrics**:
| Metric | Good | Needs Work | Poor |
|--------|------|------------|------|
| LCP (Largest Contentful Paint) | < 2.5s | 2.5-4s | > 4s |
| INP (Interaction to Next Paint) | < 200ms | 200-500ms | > 500ms |
| CLS (Cumulative Layout Shift) | < 0.1 | 0.1-0.25 | > 0.25 |
npx lighthouse https://yoursite.com --only-categories=performance

**目标指标**:
| 指标 | 良好 | 需要改进 | 较差 |
|--------|------|------------|------|
| LCP (Largest Contentful Paint) | < 2.5s | 2.5-4s | > 4s |
| INP (Interaction to Next Paint) | < 200ms | 200-500ms | > 500ms |
| CLS (Cumulative Layout Shift) | < 0.1 | 0.1-0.25 | > 0.25 |

Bundle Analysis

包分析

bash
undefined
bash
undefined

Next.js

Next.js

ANALYZE=true npm run build
ANALYZE=true npm run build

Webpack

Webpack

npx webpack-bundle-analyzer stats.json
npx webpack-bundle-analyzer stats.json

Vite

Vite

npx vite-bundle-visualizer
undefined
npx vite-bundle-visualizer
undefined

React Performance

React性能优化

React DevTools Profiler

React DevTools分析器

  1. Install React DevTools browser extension
  2. Open DevTools → Profiler tab
  3. Click Record, interact with app, stop recording
  4. Analyze flame graph for slow components
  1. 安装React DevTools浏览器扩展
  2. 打开开发者工具 → Profiler标签页
  3. 点击录制,与应用交互后停止录制
  4. 分析火焰图找出性能缓慢的组件

Common React Optimizations

常见React优化方案

tsx
// 1. Memoize expensive components
const MemoizedList = React.memo(function List({ items }) {
  return items.map(item => <Item key={item.id} {...item} />);
});

// 2. Use useMemo for expensive calculations
const sortedItems = useMemo(() => {
  return [...items].sort((a, b) => a.name.localeCompare(b.name));
}, [items]);

// 3. Use useCallback for stable function references
const handleClick = useCallback((id: string) => {
  setSelected(id);
}, []);

// 4. Virtualize long lists
import { FixedSizeList } from 'react-window';

function VirtualList({ items }) {
  return (
    <FixedSizeList
      height={400}
      itemCount={items.length}
      itemSize={50}
      width="100%"
    >
      {({ index, style }) => (
        <div style={style}>{items[index].name}</div>
      )}
    </FixedSizeList>
  );
}

// 5. Lazy load components
const HeavyComponent = React.lazy(() => import('./HeavyComponent'));

function App() {
  return (
    <Suspense fallback={<Loading />}>
      <HeavyComponent />
    </Suspense>
  );
}
tsx
// 1. 缓存开销大的组件
const MemoizedList = React.memo(function List({ items }) {
  return items.map(item => <Item key={item.id} {...item} />);
});

// 2. 使用useMemo缓存开销大的计算结果
const sortedItems = useMemo(() => {
  return [...items].sort((a, b) => a.name.localeCompare(b.name));
}, [items]);

// 3. 使用useCallback保持函数引用稳定
const handleClick = useCallback((id: string) => {
  setSelected(id);
}, []);

// 4. 虚拟化长列表
import { FixedSizeList } from 'react-window';

function VirtualList({ items }) {
  return (
    <FixedSizeList
      height={400}
      itemCount={items.length}
      itemSize={50}
      width="100%"
    >
      {({ index, style }) => (
        <div style={style}>{items[index].name}</div>
      )}
    </FixedSizeList>
  );
}

// 5. 懒加载组件
const HeavyComponent = React.lazy(() => import('./HeavyComponent'));

function App() {
  return (
    <Suspense fallback={<Loading />}>
      <HeavyComponent />
    </Suspense>
  );
}

Node.js Performance

Node.js性能优化

Profiling

性能分析

bash
undefined
bash
undefined

CPU profile

CPU分析

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

Heap snapshot

堆快照

node --inspect app.js
node --inspect app.js

Then use Chrome DevTools Memory tab

然后使用Chrome DevTools的Memory标签页

Clinic.js (comprehensive)

Clinic.js(综合工具)

npx clinic doctor -- node app.js npx clinic flame -- node app.js npx clinic bubbleprof -- node app.js
undefined
npx clinic doctor -- node app.js npx clinic flame -- node app.js npx clinic bubbleprof -- node app.js
undefined

Memory Leak Detection

内存泄漏检测

javascript
// Add to app for debugging
const used = process.memoryUsage();
console.log({
  heapUsed: `${Math.round(used.heapUsed / 1024 / 1024)} MB`,
  heapTotal: `${Math.round(used.heapTotal / 1024 / 1024)} MB`,
  external: `${Math.round(used.external / 1024 / 1024)} MB`,
});
javascript
// 添加到应用中用于调试
const used = process.memoryUsage();
console.log({
  heapUsed: `${Math.round(used.heapUsed / 1024 / 1024)} MB`,
  heapTotal: `${Math.round(used.heapTotal / 1024 / 1024)} MB`,
  external: `${Math.round(used.external / 1024 / 1024)} MB`,
});

Database Performance

数据库性能优化

sql
-- PostgreSQL: Analyze slow queries
EXPLAIN ANALYZE SELECT * FROM users WHERE email = 'test@example.com';

-- Find missing indexes
SELECT relname, seq_scan, idx_scan
FROM pg_stat_user_tables
WHERE seq_scan > idx_scan;
sql
-- PostgreSQL: 分析慢查询
EXPLAIN ANALYZE SELECT * FROM users WHERE email = 'test@example.com';

-- 查找缺失的索引
SELECT relname, seq_scan, idx_scan
FROM pg_stat_user_tables
WHERE seq_scan > idx_scan;

Query Optimization

查询优化

typescript
// Bad: N+1 query
const users = await db.user.findMany();
for (const user of users) {
  const posts = await db.post.findMany({ where: { userId: user.id } });
}

// Good: Single query with include
const users = await db.user.findMany({
  include: { posts: true }
});

// Good: Select only needed fields
const users = await db.user.findMany({
  select: { id: true, name: true, email: true }
});
typescript
// 不佳:N+1查询
const users = await db.user.findMany();
for (const user of users) {
  const posts = await db.post.findMany({ where: { userId: user.id } });
}

// 良好:单次查询并关联数据
const users = await db.user.findMany({
  include: { posts: true }
});

// 良好:仅选择所需字段
const users = await db.user.findMany({
  select: { id: true, name: true, email: true }
});

Quick Wins Checklist

快速优化清单

  • Enable gzip/brotli compression
  • Add caching headers
  • Lazy load images (
    loading="lazy"
    )
  • Preconnect to external domains
  • Use CDN for static assets
  • Minimize JavaScript bundle
  • Defer non-critical JS
  • Optimize images (WebP, proper sizing)
  • Add database indexes
  • Use connection pooling
  • 启用gzip/brotli压缩
  • 添加缓存头
  • 懒加载图片(
    loading="lazy"
  • 预连接到外部域名
  • 使用CDN托管静态资源
  • 最小化JavaScript包体积
  • 延迟加载非关键JS
  • 优化图片格式(WebP、合适尺寸)
  • 添加数据库索引
  • 使用连接池