memory-optimization

Compare original and translation side by side

🇺🇸

Original

English
🇨🇳

Translation

Chinese

Memory Optimization

内存优化

Overview

概述

Memory optimization improves application performance, stability, and reduces infrastructure costs. Efficient memory usage is critical for scalability.
内存优化可提升应用程序的性能、稳定性,并降低基础设施成本。高效的内存使用对于可扩展性至关重要。

When to Use

适用场景

  • High memory usage
  • Memory leaks suspected
  • Slow performance
  • Out of memory crashes
  • Scaling challenges
  • 内存使用率过高
  • 怀疑存在内存泄漏
  • 性能缓慢
  • 内存不足导致崩溃
  • 扩展遇到挑战

Instructions

操作指南

1. Memory Profiling

1. 内存分析

javascript
// Browser memory profiling

// Check memory usage
performance.memory: {
  jsHeapSizeLimit: 2190000000,    // Max available
  totalJSHeapSize: 1300000000,    // Total allocated
  usedJSHeapSize: 950000000       // Currently used
}

// React DevTools Profiler
- Open React DevToolsProfiler
- Record interaction
- See component renders and time
- Identify unnecessary renders

// Chrome DevTools
1. Open DevToolsMemory
2. Take heap snapshot
3. Compare before/after
4. Look for retained objects
5. Check retained sizes

// Node.js profiling
node --inspect app.js
// Open chrome://inspect
// Take heap snapshots
// Compare growth over time
javascript
// 浏览器内存分析

// 检查内存使用情况
performance.memory: {
  jsHeapSizeLimit: 2190000000,    // 最大可用内存
  totalJSHeapSize: 1300000000,    // 已分配总内存
  usedJSHeapSize: 950000000       // 当前使用内存
}

// React DevTools Profiler
- 打开React DevToolsProfiler面板
- 记录交互过程
- 查看组件渲染情况及耗时
- 识别不必要的渲染

// Chrome DevTools
1. 打开DevTools → Memory面板
2. 生成堆快照
3. 对比操作前后的快照
4. 查找被保留的对象
5. 检查保留大小

// Node.js内存分析
node --inspect app.js
// 打开 chrome://inspect
// 生成堆快照
// 随时间对比内存增长情况

2. Memory Leak Detection

2. 内存泄漏检测

python
undefined
python
undefined

Identify and fix memory leaks

识别并修复内存泄漏

class MemoryLeakDebug: def identify_leaks(self): """Common patterns""" return { 'circular_references': { 'problem': 'Objects reference each other, prevent GC', 'example': 'parent.child = child; child.parent = parent', 'solution': 'Use weak references or cleaner code' }, 'event_listeners': { 'problem': 'Listeners not removed', 'example': 'element.addEventListener(...) without removeEventListener', 'solution': 'Always remove listeners on cleanup' }, 'timers': { 'problem': 'setInterval/setTimeout not cleared', 'example': 'setInterval(() => {}, 1000) never clearInterval', 'solution': 'Store ID and clear on unmount' }, 'cache_unbounded': { 'problem': 'Cache grows without bounds', 'example': 'cache[key] = value (never deleted)', 'solution': 'Implement TTL or size limits' }, 'dom_references': { 'problem': 'Removed DOM elements still referenced', 'example': 'var x = document.getElementById("removed")', 'solution': 'Clear references after removal' } }
def detect_in_browser(self):
    """JavaScript detection"""
    return """
// Monitor memory growth setInterval(() => { const mem = performance.memory; const used = mem.usedJSHeapSize / 1000000; console.log(
Memory: ${used.toFixed(1)} MB
); }, 1000);
// If grows over time without plateau = leak """
undefined
class MemoryLeakDebug: def identify_leaks(self): """常见模式""" return { 'circular_references': { 'problem': '对象相互引用,阻止GC', 'example': 'parent.child = child; child.parent = parent', 'solution': '使用弱引用或优化代码逻辑' }, 'event_listeners': { 'problem': '监听器未被移除', 'example': 'element.addEventListener(...) 未调用 removeEventListener', 'solution': '清理时务必移除监听器' }, 'timers': { 'problem': 'setInterval/setTimeout 未被清除', 'example': 'setInterval(() => {}, 1000) 从未调用 clearInterval', 'solution': '保存定时器ID并在卸载时清除' }, 'cache_unbounded': { 'problem': '缓存无限制增长', 'example': 'cache[key] = value (从未删除)', 'solution': '实现TTL或大小限制' }, 'dom_references': { 'problem': '已移除的DOM元素仍被引用', 'example': 'var x = document.getElementById("removed")', 'solution': '移除元素后清除引用' } }
def detect_in_browser(self):
    """JavaScript检测方法"""
    return """
// 监控内存增长 setInterval(() => { const mem = performance.memory; const used = mem.usedJSHeapSize / 1000000; console.log(
内存使用量: ${used.toFixed(1)} MB
); }, 1000);
// 如果内存持续增长且没有趋于平稳,则存在泄漏 """
undefined

3. Optimization Techniques

3. 优化技巧

yaml
Memory Optimization:

Object Pooling:
  Pattern: Reuse objects instead of creating new
  Example: GameObject pool in games
  Benefits: Reduce GC, stable memory
  Trade-off: Complexity

Lazy Loading:
  Pattern: Load data only when needed
  Example: Infinite scroll
  Benefits: Lower peak memory
  Trade-off: Complexity

Pagination:
  Pattern: Process data in chunks
  Example: 1M records → 1K per page
  Benefits: Constant memory
  Trade-off: More requests

Stream Processing:
  Pattern: Process one item at a time
  Example: fs.createReadStream()
  Benefits: Constant memory for large data
  Trade-off: Slower if cached

Memoization:
  Pattern: Cache expensive calculations
  Benefits: Faster, reuse results
  Trade-off: Memory for speed

---

Framework-Specific:

React:
  - useMemo for expensive calculations
  - useCallback to avoid creating functions
  - Code splitting / lazy loading
  - Windowing for long lists (react-window)

Node.js:
  - Stream instead of loadFile
  - Limit cluster workers
  - Set heap size: --max-old-space-size=4096
  - Monitor with clinic.js

---

GC (Garbage Collection):

Minimize:
  - Object creation
  - Large allocations
  - Frequent new objects
  - String concatenation

Example (Bad):
let result = "";
for (let i = 0; i < 1000000; i++) {
  result += i.toString() + ",";
  // Creates new string each iteration
}

Example (Good):
const result = Array.from(
  {length: 1000000},
  (_, i) => i.toString()
).join(",");
// Single allocation
yaml
内存优化:

对象池模式:
  模式: 复用对象而非创建新对象
  示例: 游戏中的游戏对象池
  优势: 减少GC次数,内存稳定
  权衡点: 实现复杂度提升

懒加载:
  模式: 仅在需要时加载数据
  示例: 无限滚动
  优势: 降低峰值内存占用
  权衡点: 实现复杂度提升

分页处理:
  模式: 分块处理数据
  示例: 100万条记录 → 每页1000条
  优势: 内存占用保持稳定
  权衡点: 请求次数增加

流处理:
  模式: 逐个处理数据项
  示例: fs.createReadStream()
  优势: 处理大数据时内存占用稳定
  权衡点: 若使用缓存则速度较慢

记忆化:
  模式: 缓存耗时计算的结果
  优势: 速度更快,复用计算结果
  权衡点: 以内存换取速度

---

框架专属优化:

React:
  - useMemo用于缓存耗时计算结果
  - useCallback避免重复创建函数
  - 代码分割/懒加载
  - 长列表使用窗口化处理(react-window)

Node.js:
  - 使用流而非加载整个文件
  - 限制集群工作进程数量
  - 设置堆大小: --max-old-space-size=4096
  - 使用clinic.js进行监控

---

GC(垃圾回收):

需尽量减少:
  - 对象创建
  - 大块内存分配
  - 频繁创建新对象
  - 字符串拼接

示例(不良实践):
let result = "";
for (let i = 0; i < 1000000; i++) {
  result += i.toString() + ",";
  // 每次迭代都会创建新字符串
}

示例(良好实践):
const result = Array.from(
  {length: 1000000},
  (_, i) => i.toString()
).join(",");
// 仅一次内存分配

4. Monitoring & Targets

4. 监控与指标

yaml
Memory Targets:

Web App:
  Initial: <10MB
  After use: <50MB
  Peak: <100MB
  Leak check: Should plateau

Node.js API:
  Per-process: 100-500MB
  Cluster total: 1-4GB
  Heap size: Monitor vs available RAM

Mobile:
  Initial: <20MB
  Working: <50MB
  Peak: <100MB (device dependent)

---

Tools:

Browser:
  - Chrome DevTools Memory
  - Firefox DevTools Memory
  - React DevTools Profiler
  - Redux DevTools

Node.js:
  - node --inspect
  - clinic.js
  - nodemon --exec with monitoring
  - New Relic / DataDog

Monitoring:
  - Application Performance Monitoring (APM)
  - Prometheus + Grafana
  - CloudWatch
  - New Relic

---

Checklist:

[ ] Profile baseline memory
[ ] Identify heavy components
[ ] Remove event listeners on cleanup
[ ] Clear timers on cleanup
[ ] Implement lazy loading
[ ] Use pagination for large lists
[ ] Monitor memory trends
[ ] Set up GC monitoring
[ ] Test with production data volume
[ ] Stress test for leaks
[ ] Establish memory budget
[ ] Set up alerts
yaml
内存指标目标:

Web应用:
  初始状态: <10MB
  使用后: <50MB
  峰值: <100MB
  泄漏检查: 内存占用应趋于平稳

Node.js API:
  单进程: 100-500MB
  集群总内存: 1-4GB
  堆大小: 监控可用RAM对比情况

移动应用:
  初始状态: <20MB
  运行中: <50MB
  峰值: <100MB(取决于设备)

---

工具:

浏览器:
  - Chrome DevTools Memory面板
  - Firefox DevTools Memory面板
  - React DevTools Profiler
  - Redux DevTools

Node.js:
  - node --inspect
  - clinic.js
  - nodemon --exec 搭配监控
  - New Relic / DataDog

监控方案:
  - 应用性能监控(APM)
  - Prometheus + Grafana
  - CloudWatch
  - New Relic

---

检查清单:

[ ] 记录基准内存数据
[ ] 识别内存占用高的组件
[ ] 清理时移除事件监听器
[ ] 清理时清除定时器
[ ] 实现懒加载
[ ] 大数据列表使用分页
[ ] 监控内存趋势
[ ] 配置GC监控
[ ] 使用生产级数据量测试
[ ] 压力测试检查泄漏
[ ] 制定内存预算
[ ] 设置告警规则

Key Points

核心要点

  • Take baseline memory measurements
  • Use profilers to identify issues
  • Remove listeners and timers on cleanup
  • Implement streaming for large data
  • Use lazy loading and pagination
  • Monitor GC pause times
  • Set heap size appropriate for workload
  • Object pooling for frequent allocations
  • Regular memory testing with real data
  • Alert on memory growth trends
  • 记录基准内存测量数据
  • 使用分析工具识别问题
  • 清理时移除监听器和定时器
  • 对大数据使用流处理
  • 采用懒加载和分页
  • 监控GC暂停时间
  • 根据工作负载设置合适的堆大小
  • 频繁分配场景使用对象池
  • 定期使用真实数据进行内存测试
  • 针对内存增长趋势设置告警