remotion-performance-optimizer

Compare original and translation side by side

🇺🇸

Original

English
🇨🇳

Translation

Chinese

Remotion Performance Optimizer

Remotion 性能优化器

Comprehensive performance analysis and optimization recommendations for Remotion video compositions. Identifies bottlenecks and provides actionable fixes to reduce render times.
针对Remotion视频合成项目的全面性能分析与优化建议。识别性能瓶颈并提供可落地的修复方案,以缩短渲染时长。

What This Skill Does

该技能的功能

Performs deep performance analysis:
  1. Computation analysis — Identify expensive operations in render path
  2. Re-render detection — Find unnecessary component re-renders
  3. Asset optimization — Recommend asset size and format improvements
  4. Memoization opportunities — Identify cacheable calculations
  5. Architecture review — Suggest structural improvements
  6. Render profiling — Analyze frame render times
执行深度性能分析:
  1. 计算分析 — 识别渲染路径中的耗时操作
  2. 重渲染检测 — 发现不必要的组件重渲染
  3. 资源优化 — 建议资源尺寸与格式的改进方案
  4. 缓存优化点识别 — 找出可缓存的计算逻辑
  5. 架构评审 — 提出结构改进建议
  6. 渲染性能分析 — 分析单帧渲染时长

Input/Output Formats

输入/输出格式

Input Format: Remotion Composition Code

输入格式:Remotion合成代码

Accepts implemented Remotion composition files:
Files to analyze:
src/remotion/compositions/VideoName/
├── index.tsx           # Main composition
├── constants.ts        # Color, timing, spring configs
├── types.ts            # TypeScript types
└── scenes/
    ├── Scene1.tsx
    ├── Scene2.tsx
    └── Scene3.tsx
Context needed:
  • Target render time goals (e.g., < 100ms/frame)
  • Composition complexity (simple, moderate, complex)
  • Any specific performance concerns
Example request:
Analyze performance of VideoName composition.
Target: < 100ms/frame average render time.
Scene 2 is rendering slowly (200ms/frame).
接受已实现的Remotion合成文件:
待分析文件结构:
src/remotion/compositions/VideoName/
├── index.tsx           # 主合成文件
├── constants.ts        # 颜色、时序、弹簧配置
├── types.ts            # TypeScript类型定义
└── scenes/
    ├── Scene1.tsx
    ├── Scene2.tsx
    └── Scene3.tsx
所需上下文:
  • 目标渲染时长(例如:< 100ms/帧)
  • 合成项目复杂度(简单、中等、复杂)
  • 任何特定的性能担忧点
示例请求:
分析VideoName合成项目的性能。
目标:平均渲染时长 < 100ms/帧。
Scene 2渲染缓慢(200ms/帧)。

Output Format: OPTIMIZATION_REPORT.md

输出格式:OPTIMIZATION_REPORT.md

Generates detailed performance analysis with actionable fixes:
markdown
undefined
生成包含可落地修复方案的详细性能分析报告:
markdown
undefined

Performance Optimization Report: [Video Title]

性能优化报告:[视频标题]

Date: 2026-01-23 Analyzer: remotion-performance-optimizer Composition:
src/remotion/compositions/VideoName/

日期: 2026-01-23 分析工具: remotion-performance-optimizer 合成项目:
src/remotion/compositions/VideoName/

Executive Summary

执行摘要

Current Performance: ⚠️ NEEDS OPTIMIZATION
MetricCurrentTargetStatus
Average Render Time145ms/frame< 100ms🔴 45% over target
Slowest SceneScene 2: 285ms< 150ms🔴 90% over target
Total Render Time (estimated)36 minutes< 20 minutes🔴 80% over target
Memory UsageNormalNormal🟢 Good
Potential Improvement: 60-70% faster render times after implementing recommendations
Priority Actions:
  1. Replace Math.random() with seeded random in Scene 2 (55% improvement)
  2. Optimize large product image (20% faster asset loading)
  3. Extract repeated spring calculations (15% improvement)

当前性能: ⚠️ 需要优化
指标当前值目标值状态
平均渲染时长145ms/帧< 100ms🔴 超出目标45%
最慢场景Scene 2: 285ms< 150ms🔴 超出目标90%
预估总渲染时长36分钟< 20分钟🔴 超出目标80%
内存占用正常正常🟢 良好
潜在提升空间: 实施建议后,渲染速度可提升60-70%
优先行动项:
  1. 在Scene 2中用种子随机数替换Math.random()(提升55%)
  2. 优化大型产品图片(资源加载速度提升20%)
  3. 提取重复的spring计算逻辑(提升15%)

Performance Breakdown by Scene

各场景性能细分

SceneAvg Render TimeStatusPrimary Bottleneck
Scene 175ms🟢 GoodNone
Scene 2285ms🔴 CriticalNon-deterministic particle system
Scene 395ms🟡 AcceptableLarge asset loading
Scene 480ms🟢 GoodNone
Overall: 145ms average (Target: < 100ms)

场景平均渲染时长状态主要瓶颈
Scene 175ms🟢 良好
Scene 2285ms🔴 严重非确定性粒子系统
Scene 395ms🟡 可接受大型资源加载
Scene 480ms🟢 良好
整体情况: 平均145ms/帧(目标:< 100ms)

Issues Found

发现的问题

CRITICAL (Major Performance Impact)

严重(对性能影响重大)

1. Non-Deterministic Particle System in Scene 2

1. Scene 2中的非确定性粒子系统

Impact: 🔴 200ms per frame slowdown Location:
src/remotion/compositions/VideoName/scenes/Scene2.tsx:48-65
Severity: Critical - 70% of render time in Scene 2
Problem:
typescript
// ❌ PROBLEM: Math.random() called 70 times per frame
{Array.from({ length: 70 }, (_, i) => {
  const x = Math.random() * width;     // Recalculated every frame!
  const y = Math.random() * height;    // Non-deterministic
  const speed = Math.random() * 2;

  return <Particle key={i} x={x} y={y} speed={speed} />;
})}
Why This Is Slow:
  • Math.random() is non-deterministic (different each frame)
  • 70 particles × 3 random calls = 210 random calls per frame
  • Remotion can't cache because values change
  • Browser must recalculate positions every frame
Solution:
typescript
// ✅ OPTIMIZED: Seeded random, deterministic
const seededRandom = (seed: number): number => {
  const x = Math.sin(seed) * 10000;
  return x - Math.floor(x);
};

const particles = useMemo(
  () => Array.from({ length: 70 }, (_, i) => ({
    x: seededRandom(i * 123.456) * width,
    y: seededRandom(i * 789.012) * height,
    speed: seededRandom(i * 456.789) * 2,
  })),
  [width, height]
);

{particles.map((p, i) => (
  <Particle key={i} x={p.x} y={p.y} speed={p.speed} />
))}
Expected Improvement:
  • Scene 2: 285ms → 125ms (55% faster)
  • Overall: 145ms → 105ms (28% faster)
  • Total render time: 36min → 22min (40% faster)
Implementation Time: 15 minutes

影响: 🔴 每帧慢200ms 位置:
src/remotion/compositions/VideoName/scenes/Scene2.tsx:48-65
严重程度: 严重 - 占Scene 2渲染时长的70%
问题:
typescript
// ❌ 问题:每帧调用70次Math.random()
{Array.from({ length: 70 }, (_, i) => {
  const x = Math.random() * width;     // 每帧重新计算!
  const y = Math.random() * height;    // 非确定性
  const speed = Math.random() * 2;

  return <Particle key={i} x={x} y={y} speed={speed} />;
})}
为何缓慢:
  • Math.random()具有非确定性(每帧结果不同)
  • 70个粒子 × 3次随机调用 = 每帧210次随机计算
  • Remotion无法缓存,因为值每帧变化
  • 浏览器必须每帧重新计算位置
解决方案:
typescript
// ✅ 优化:种子随机数,确定性结果
const seededRandom = (seed: number): number => {
  const x = Math.sin(seed) * 10000;
  return x - Math.floor(x);
};

const particles = useMemo(
  () => Array.from({ length: 70 }, (_, i) => ({
    x: seededRandom(i * 123.456) * width,
    y: seededRandom(i * 789.012) * height,
    speed: seededRandom(i * 456.789) * 2,
  })),
  [width, height]
);

{particles.map((p, i) => (
  <Particle key={i} x={p.x} y={p.y} speed={p.speed} />
))}
预期提升:
  • Scene 2:285ms → 125ms(快55%)
  • 整体:145ms → 105ms(快28%)
  • 总渲染时长:36分钟 → 22分钟(快40%)
实施时间: 15分钟

HIGH (Significant Performance Impact)

高(对性能影响显著)

2. Large Unoptimized Product Image

2. 未优化的大型产品图片

Impact: 🟡 50ms asset loading delay Location:
public/images/product.png
Severity: High - Affects loading and memory
Problem:
Current Asset:
- Format: PNG (unnecessary transparency)
- Resolution: 4000x3000 (2x larger than needed)
- File Size: 8.2MB
- Load Time: ~50ms
Why This Is Slow:
  • 8.2MB file takes time to load and decode
  • 4000x3000 is overkill for 1920x1080 display
  • PNG format unnecessary (no transparency used)
Solution:
bash
undefined
影响: 🟡 资源加载延迟50ms 位置:
public/images/product.png
严重程度: 高 - 影响加载与内存
问题:
当前资源:
- 格式:PNG(无需透明通道)
- 分辨率:4000x3000(超出需求2倍)
- 文件大小:8.2MB
- 加载时长:~50ms
为何缓慢:
  • 8.2MB文件加载与解码耗时
  • 4000x3000分辨率对于1920x1080显示来说性能过剩
  • 无需使用PNG格式(未用到透明通道)
解决方案:
bash
undefined

Resize and convert to JPEG

调整尺寸并转换为JPEG

magick public/images/product.png
-resize 1920x1440
-quality 90
public/images/product.jpg
magick public/images/product.png
-resize 1920x1440
-quality 90
public/images/product.jpg

Update code

更新代码

<Img src={staticFile('images/product.jpg')} />

**Result:**
Optimized Asset:
  • Format: JPEG
  • Resolution: 1920x1440 (2x for retina)
  • File Size: ~400KB (95% smaller)
  • Load Time: ~5ms (90% faster)

**Expected Improvement:**
- Scene 3 load time: 50ms faster
- Overall render: 95ms → 85ms in Scene 3
- Smaller final video file

**Implementation Time:** 5 minutes

---
<Img src={staticFile('images/product.jpg')} />

**优化后结果:**
优化后资源:
  • 格式:JPEG
  • 分辨率:1920x1440(适配视网膜屏的2倍尺寸)
  • 文件大小:~400KB(缩小95%)
  • 加载时长:~5ms(快90%)

**预期提升:**
- Scene 3加载时长减少50ms
- Scene 3渲染时长:95ms → 85ms
- 最终视频文件更小

**实施时间:** 5分钟

---

3. Repeated Spring Calculations

3. 重复的spring计算

Impact: 🟡 30ms per scene Location: Multiple scenes Severity: High - Accumulates across scenes
Problem in Scene 1:
typescript
// ❌ PROBLEM: Spring calculated 3 times
<div style={{
  opacity: spring({ frame, fps, config: SMOOTH }),
  scale: spring({ frame, fps, config: SMOOTH }),
  y: interpolate(spring({ frame, fps, config: SMOOTH }), [0, 1], [0, 100]),
}} />
Why This Is Slow:
  • Spring function has internal calculations
  • Called 3 times with identical parameters
  • Remotion can't optimize duplicate calls
  • Wastes 20-30ms per scene
Solution:
typescript
// ✅ OPTIMIZED: Calculate once, reuse
const progress = spring({ frame, fps, config: SMOOTH });

<div style={{
  opacity: progress,
  scale: progress,
  y: interpolate(progress, [0, 1], [0, 100]),
}} />
Expected Improvement:
  • Per scene: 20-30ms faster
  • Overall: 145ms → 125ms (15% faster)
  • Affects Scenes 1, 3, 4
Implementation Time: 10 minutes

影响: 🟡 每个场景慢30ms 位置: 多个场景 严重程度: 高 - 影响累积到所有场景
Scene 1中的问题:
typescript
// ❌ 问题:spring计算执行3次
<div style={{
  opacity: spring({ frame, fps, config: SMOOTH }),
  scale: spring({ frame, fps, config: SMOOTH }),
  y: interpolate(spring({ frame, fps, config: SMOOTH }), [0, 1], [0, 100]),
}} />
为何缓慢:
  • spring函数包含内部计算逻辑
  • 相同参数调用3次
  • Remotion无法优化重复调用
  • 每个场景浪费20-30ms
解决方案:
typescript
// ✅ 优化:计算一次,重复使用
const progress = spring({ frame, fps, config: SMOOTH });

<div style={{
  opacity: progress,
  scale: progress,
  y: interpolate(progress, [0, 1], [0, 100]),
}} />
预期提升:
  • 每个场景快20-30ms
  • 整体:145ms → 125ms(快15%)
  • 影响Scene 1、3、4
实施时间: 10分钟

MEDIUM (Moderate Performance Impact)

中等(对性能影响适中)

4. Component Not Memoized

4. 组件未缓存

Impact: 🟡 10-15ms Location: Scene components Severity: Medium - Minor unnecessary re-renders
Problem:
typescript
// Scene components re-render even when props haven't changed
function Scene1() { ... }
function Scene2() { ... }
Solution:
typescript
import { memo } from 'react';

const Scene1 = memo(() => { ... });
const Scene2 = memo(() => { ... });
Expected Improvement:
  • 10-15ms per scene
  • Overall: 10% faster in complex compositions
Implementation Time: 5 minutes

影响: 🟡 10-15ms 位置: 场景组件 严重程度: 中等 - 轻微的不必要重渲染
问题:
typescript
// 场景组件即使props未变化也会重渲染
function Scene1() { ... }
function Scene2() { ... }
解决方案:
typescript
import { memo } from 'react';

const Scene1 = memo(() => { ... });
const Scene2 = memo(() => { ... });
预期提升:
  • 每个场景快10-15ms
  • 复杂合成项目整体快10%
实施时间: 5分钟

LOW (Minor Performance Impact)

低(对性能影响轻微)

5. Array Creation in Render

5. 渲染函数中创建数组

Impact: 🟢 2-5ms Location:
Scene4.tsx:23
Severity: Low - Negligible but fixable
Problem:
typescript
// Array recreated every frame
{Array(50).fill(0).map((_, i) => <Element key={i} />)}
Solution:
typescript
// Reuse array reference
const ELEMENTS = Array.from({ length: 50 }, (_, i) => i);

{ELEMENTS.map((i) => <Element key={i} />)}
Expected Improvement: 2-5ms (minimal but good practice)
Implementation Time: 2 minutes

影响: 🟢 2-5ms 位置:
Scene4.tsx:23
严重程度: 低 - 影响可忽略但可修复
问题:
typescript
// 每帧重新创建数组
{Array(50).fill(0).map((_, i) => <Element key={i} />)}
解决方案:
typescript
// 复用数组引用
const ELEMENTS = Array.from({ length: 50 }, (_, i) => i);

{ELEMENTS.map((i) => <Element key={i} />)}
预期提升: 2-5ms(影响极小但属于最佳实践)
实施时间: 2分钟

Optimization Implementation Plan

优化实施计划

Phase 1: Critical Fixes (15 minutes) — 55% improvement

第一阶段:严重问题修复(15分钟)— 提升55%

  1. Replace Math.random() with seeded random in Scene 2
    • Expected: 285ms → 125ms
  1. 在Scene 2中用种子随机数替换Math.random()
    • 预期:285ms → 125ms

Phase 2: High Priority (15 minutes) — 20% additional improvement

第二阶段:高优先级修复(15分钟)— 额外提升20%

  1. Optimize product.png to JPEG (5 min)
    • Expected: 95ms → 85ms in Scene 3
  2. Extract spring calculations (10 min)
    • Expected: 145ms → 125ms overall
  1. 将product.png优化为JPEG(5分钟)
    • 预期:Scene 3从95ms → 85ms
  2. 提取spring计算逻辑(10分钟)
    • 预期:整体从145ms → 125ms

Phase 3: Medium Priority (10 minutes) — 10% additional improvement

第三阶段:中等优先级修复(10分钟)— 额外提升10%

  1. Memoize scene components
    • Expected: 10-15ms improvement
  1. 缓存场景组件
    • 预期:提升10-15ms

Phase 4: Low Priority (5 minutes) — 2-5% improvement

第四阶段:低优先级修复(5分钟)— 额外提升2-5%

  1. Extract array constants
    • Expected: 2-5ms improvement
Total Implementation Time: 45 minutes Total Expected Improvement: 60-70% faster renders

  1. 提取数组常量
    • 预期:提升2-5ms
总实施时间: 45分钟 总预期提升: 渲染速度加快60-70%

Before/After Projections

优化前后预估对比

MetricBeforeAfter Phase 1After Phase 2After AllTarget
Scene 2285ms125ms115ms110ms< 150ms ✅
Scene 395ms95ms85ms80ms< 100ms ✅
Overall Avg145ms105ms90ms85ms< 100ms ✅
Total Render36min22min19min18min< 20min ✅
After all optimizations: All targets met! 🎉

指标优化前第一阶段后第二阶段后全部完成后目标值
Scene 2285ms125ms115ms110ms< 150ms ✅
Scene 395ms95ms85ms80ms< 100ms ✅
整体平均145ms105ms90ms85ms< 100ms ✅
总渲染时长36分钟22分钟19分钟18分钟< 20分钟 ✅
全部优化完成后: 所有目标均达成! 🎉

Performance Validation

性能验证

Benchmarking Commands

基准测试命令

bash
undefined
bash
undefined

Test single frame render time

测试单帧渲染时长

npx remotion still src/index.tsx VideoName --frame=150
npx remotion still src/index.tsx VideoName --frame=150

Profile specific scene (Scene 2)

分析特定场景(Scene 2)

npx remotion still src/index.tsx VideoName --frame=225
npx remotion still src/index.tsx VideoName --frame=225

Benchmark full render (first 100 frames)

基准测试完整渲染(前100帧)

time npx remotion render src/index.tsx VideoName test.mp4 --frames=0-100
time npx remotion render src/index.tsx VideoName test.mp4 --frames=0-100

Full production render with timing

带计时的完整生产环境渲染

time npx remotion render src/index.tsx VideoName output.mp4
undefined
time npx remotion render src/index.tsx VideoName output.mp4
undefined

Performance Targets

性能目标

Composition TypeTargetCurrentStatus
Simple scenes< 50ms75ms (Scenes 1,4)🟡 Acceptable
Moderate scenes< 100ms145ms avg🔴 Over target
Complex scenes< 150ms285ms (Scene 2)🔴 Over target
After optimizations: All scenes should meet targets

合成项目类型目标值当前值状态
简单场景< 50ms75ms(Scene 1、4)🟡 可接受
中等场景< 100ms平均145ms🔴 超出目标
复杂场景< 150ms285ms(Scene 2)🔴 超出目标
优化完成后: 所有场景均应达标

Code Quality Checks

代码质量检查

Good Patterns Found:
  • Constants extracted (COLORS, SPRING_CONFIGS)
  • useVideoConfig used for responsive sizing
  • TypeScript types defined
  • staticFile() used for assets
⚠️ Optimization Opportunities:
  • Replace Math.random() with seeded random
  • Extract repeated spring calculations
  • Memoize scene components
  • Optimize large assets

发现的良好实践:
  • 常量已提取(COLORS、SPRING_CONFIGS)
  • 使用useVideoConfig实现响应式尺寸
  • 定义了TypeScript类型
  • 使用staticFile()加载资源
⚠️ 可优化点:
  • 用种子随机数替换Math.random()
  • 提取重复的spring计算逻辑
  • 缓存场景组件
  • 优化大型资源

Asset Optimization Details

资源优化详情

Current Assets

当前资源

AssetSizeFormatStatusRecommendation
logo.png180KBPNG🟢 GoodKeep as-is
product.png8.2MBPNG🔴 Optimize→ JPEG 400KB
background.mp31.8MBMP3🟢 GoodKeep as-is
whoosh.mp345KBMP3🟢 GoodKeep as-is
资源大小格式状态建议
logo.png180KBPNG🟢 良好保持原样
product.png8.2MBPNG🔴 需要优化→ JPEG 400KB
background.mp31.8MBMP3🟢 良好保持原样
whoosh.mp345KBMP3🟢 良好保持原样

Optimization Commands

优化命令

bash
undefined
bash
undefined

Product image (95% size reduction)

产品图片(缩小95%)

magick public/images/product.png
-resize 1920x1440
-quality 90
public/images/product.jpg

---
magick public/images/product.png
-resize 1920x1440
-quality 90
public/images/product.jpg

---

Recommendations Summary

建议总结

Immediate Actions (Critical)

立即行动(严重)

  1. Replace Math.random() in Scene 2 — 55% faster
    • Priority: CRITICAL
    • Time: 15 minutes
    • Impact: 160ms per frame improvement
  1. 替换Scene 2中的Math.random() — 快55%
    • 优先级:严重
    • 时间:15分钟
    • 影响:每帧提升160ms

Short-Term Actions (High Priority)

短期行动(高优先级)

  1. Optimize product image — 20% faster loading
    • Priority: HIGH
    • Time: 5 minutes
    • Impact: 50ms improvement
  2. Extract spring calculations — 15% faster
    • Priority: HIGH
    • Time: 10 minutes
    • Impact: 20-30ms per scene
  1. 优化产品图片 — 加载速度提升20%
    • 优先级:高
    • 时间:5分钟
    • 影响:提升50ms
  2. 提取spring计算逻辑 — 快15%
    • 优先级:高
    • 时间:10分钟
    • 影响:每个场景提升20-30ms

Long-Term Improvements (Medium/Low)

长期改进(中等/低优先级)

  1. Memoize scene components (10% improvement)
  2. Extract array constants (2-5% improvement)
  3. Consider lazy loading assets
  4. Profile with Chrome DevTools for deeper analysis

  1. 缓存场景组件(提升10%)
  2. 提取数组常量(提升2-5%)
  3. 考虑资源懒加载
  4. 使用Chrome DevTools进行深度分析

Next Steps

后续步骤

  1. Implement Critical Fix: Replace Math.random() (highest impact)
  2. Benchmark: Verify Scene 2 improvement (should be 285ms → 125ms)
  3. Implement High Priority: Optimize assets and springs
  4. Re-run analysis: Verify all targets met
  5. Final render: Generate production video with optimizations

  1. 修复严重问题: 替换Math.random()(影响最大)
  2. 基准测试: 验证Scene 2的性能提升(应从285ms → 125ms)
  3. 实施高优先级修复: 优化资源与spring计算
  4. 重新分析: 验证所有目标达成
  5. 最终渲染: 生成优化后的生产环境视频

Tools & Resources

工具与资源

Profiling Tools

性能分析工具

bash
undefined
bash
undefined

Remotion built-in profiling

Remotion内置分析工具

npx remotion preview --log=verbose
npx remotion preview --log=verbose

Chrome DevTools profiling

Chrome DevTools分析

Open preview → DevTools → Performance tab → Record

打开预览 → DevTools → Performance标签 → 录制

undefined
undefined

Optimization References

优化参考文档



Approval

审批

Status: ⚠️ OPTIMIZATION REQUIRED BEFORE PRODUCTION
After implementing critical and high-priority fixes, this composition will meet all performance targets and be production-ready.
Estimated Time to Production-Ready: 30-45 minutes of optimization work
Signed: remotion-performance-optimizer Date: 2026-01-23

**This document provides:**
- Current vs. target performance metrics
- Prioritized issues by impact (CRITICAL, HIGH, MEDIUM, LOW)
- Before/after projections with concrete numbers
- Specific code locations and fixes
- Implementation time estimates
- Step-by-step optimization plan
- Benchmarking commands for validation
- Asset optimization recommendations

**Feeds into:**
- Developer: Implement fixes
- Re-run `/remotion-video-reviewer` after optimizations
- Final production render
状态: ⚠️ 上线前需完成优化
完成严重与高优先级修复后,该合成项目将满足所有性能目标,可投入生产环境。
预估优化至可上线时间: 30-45分钟
签名: remotion-performance-optimizer 日期: 2026-01-23

**该文档包含:**
- 当前与目标性能指标对比
- 按影响优先级划分的问题(严重、高、中等、低)
- 具体的优化前后预估数据
- 问题的具体代码位置与修复方案
- 实施时间预估
- 分步优化计划
- 用于验证的基准测试命令
- 资源优化建议

**对接流程:**
- 开发者:实施修复方案
- 优化完成后重新运行`/remotion-video-reviewer`
- 生成最终生产环境视频

Performance Analysis Categories

性能分析类别

1. Expensive Computations

1. 耗时计算

Issue: Calculations executed every frame unnecessarily.
Detection:
typescript
// ❌ PROBLEM - Recalculated every frame
function Scene() {
  const frame = useCurrentFrame();

  // Heavy calculation every frame
  const particles = Array.from({ length: 1000 }, () => ({
    x: Math.random() * 1920,
    y: Math.random() * 1080,
  }));

  return /* render particles */;
}
Solution:
typescript
// ✓ OPTIMIZED - Deterministic, seeded
function Scene() {
  const frame = useCurrentFrame();

  // Deterministic calculation
  const particles = useMemo(
    () => Array.from({ length: 1000 }, (_, i) => ({
      x: seededRandom(i * 123) * 1920,
      y: seededRandom(i * 456) * 1080,
    })),
    [] // No dependencies, calculate once
  );

  return /* render particles */;
}

// Seeded random for consistency
const seededRandom = (seed: number) => {
  const x = Math.sin(seed) * 10000;
  return x - Math.floor(x);
};
Impact: 30-50% render time reduction for scenes with many elements.
问题: 不必要的每帧计算逻辑。
检测示例:
typescript
// ❌ 问题 - 每帧重新计算
function Scene() {
  const frame = useCurrentFrame();

  // 每帧执行的重型计算
  const particles = Array.from({ length: 1000 }, () => ({
    x: Math.random() * 1920,
    y: Math.random() * 1080,
  }));

  return /* 渲染粒子 */;
}
解决方案:
typescript
// ✓ 优化 - 确定性、种子随机数
function Scene() {
  const frame = useCurrentFrame();

  // 确定性计算
  const particles = useMemo(
    () => Array.from({ length: 1000 }, (_, i) => ({
      x: seededRandom(i * 123) * 1920,
      y: seededRandom(i * 456) * 1080,
    })),
    [] // 无依赖,仅计算一次
  );

  return /* 渲染粒子 */;
}

// 用于保持一致性的种子随机数
const seededRandom = (seed: number) => {
  const x = Math.sin(seed) * 10000;
  return x - Math.floor(x);
};
影响: 包含大量元素的场景渲染时长可减少30-50%。

2. Repeated Spring Calculations

2. 重复的spring计算

Issue: Same spring calculation multiple times.
Detection:
typescript
// ❌ PROBLEM - Spring calculated 3 times
<div style={{
  opacity: spring({ frame, fps, config: SMOOTH }),
  scale: spring({ frame, fps, config: SMOOTH }),
  y: interpolate(spring({ frame, fps, config: SMOOTH }), [0, 1], [0, 100]),
}} />
Solution:
typescript
// ✓ OPTIMIZED - Calculate once, reuse
const progress = spring({ frame, fps, config: SMOOTH });

<div style={{
  opacity: progress,
  scale: progress,
  y: interpolate(progress, [0, 1], [0, 100]),
}} />
Impact: 10-20% render time reduction per scene.
问题: 相同的spring计算执行多次。
检测示例:
typescript
// ❌ 问题 - spring计算执行3次
<div style={{
  opacity: spring({ frame, fps, config: SMOOTH }),
  scale: spring({ frame, fps, config: SMOOTH }),
  y: interpolate(spring({ frame, fps, config: SMOOTH }), [0, 1], [0, 100]),
}} />
解决方案:
typescript
// ✓ 优化 - 计算一次,重复使用
const progress = spring({ frame, fps, config: SMOOTH });

<div style={{
  opacity: progress,
  scale: progress,
  y: interpolate(progress, [0, 1], [0, 100]),
}} />
影响: 每个场景的渲染时长可减少10-20%。

3. Large Asset Sizes

3. 大型资源

Issue: Unoptimized assets slow down loading and rendering.
Detection:
markdown
Product image: 4000x3000 PNG (8.2MB)
Background video: 3840x2160 ProRes (450MB)
Logo: 2000x2000 PNG (1.5MB)
Recommendations:
markdown
✓ Product image: 1920x1440 JPEG 90% (400KB) — 95% smaller
✓ Background video: 1920x1080 H.264 (25MB) — 95% smaller
✓ Logo: 800x800 PNG optimized (80KB) — 95% smaller
Impact: Faster renders, smaller output files, better preview performance.
问题: 未优化的资源减慢加载与渲染速度。
检测示例:
markdown
产品图片:4000x3000 PNG(8.2MB)
背景视频:3840x2160 ProRes(450MB)
Logo:2000x2000 PNG(1.5MB)
建议:
markdown
✓ 产品图片:1920x1440 JPEG 90%(400KB) — 缩小95%
✓ 背景视频:1920x1080 H.264(25MB) — 缩小95%
✓ Logo:800x800 优化PNG(80KB) — 缩小95%
影响: 渲染更快、输出文件更小、预览性能更佳。

4. Unnecessary Re-renders

4. 不必要的重渲染

Issue: Components re-render when dependencies haven't changed.
Detection:
typescript
// ❌ PROBLEM - Re-renders on every frame change
function ExpensiveComponent({ data }) {
  // Heavy calculation
  const processed = data.map(item => /* complex transform */);

  return /* render */;
}

// Parent re-renders every frame
<ExpensiveComponent data={staticData} />
Solution:
typescript
// ✓ OPTIMIZED - Memoized component
const ExpensiveComponent = memo(({ data }) => {
  // Heavy calculation
  const processed = useMemo(
    () => data.map(item => /* complex transform */),
    [data]
  );

  return /* render */;
});

// Or: Extract static data outside component
const processedData = staticData.map(item => /* complex transform */);

function Scene() {
  return <Component data={processedData} />;
}
Impact: 20-40% render time reduction for complex components.
问题: 依赖未变化时组件仍重渲染。
检测示例:
typescript
// ❌ 问题 - 每帧变化时重渲染
function ExpensiveComponent({ data }) {
  // 重型计算
  const processed = data.map(item => /* 复杂转换 */);

  return /* 渲染 */;
}

// 父组件每帧重渲染
<ExpensiveComponent data={staticData} />
解决方案:
typescript
// ✓ 优化 - 缓存组件
const ExpensiveComponent = memo(({ data }) => {
  // 重型计算
  const processed = useMemo(
    () => data.map(item => /* 复杂转换 */),
    [data]
  );

  return /* 渲染 */;
});

// 或:将静态数据提取到组件外部
const processedData = staticData.map(item => /* 复杂转换 */);

function Scene() {
  return <Component data={processedData} />;
}
影响: 复杂组件的渲染时长可减少20-40%。

5. DOM Thrashing

5. DOM抖动

Issue: Excessive DOM reads/writes causing layout thrashing.
Detection:
typescript
// ❌ PROBLEM - Reading and writing in loop
elements.forEach((el) => {
  const width = el.getBoundingClientRect().width; // Read
  el.style.width = `${width * 2}px`; // Write (causes reflow)
});
Solution:
typescript
// ✓ OPTIMIZED - Batch reads, then batch writes
const widths = elements.map((el) => el.getBoundingClientRect().width);
elements.forEach((el, i) => {
  el.style.width = `${widths[i] * 2}px`;
});
Impact: 15-30% improvement in DOM-heavy scenes.
问题: 过多的DOM读写导致布局抖动。
检测示例:
typescript
// ❌ 问题 - 循环中交替读写
elements.forEach((el) => {
  const width = el.getBoundingClientRect().width; // 读取
  el.style.width = `${width * 2}px`; // 写入(导致重排)
});
解决方案:
typescript
// ✓ 优化 - 批量读取,再批量写入
const widths = elements.map((el) => el.getBoundingClientRect().width);
elements.forEach((el, i) => {
  el.style.width = `${widths[i] * 2}px`;
});
影响: 大量DOM操作的场景性能可提升15-30%。

6. Unoptimized Loops

6. 未优化的循环

Issue: Inefficient iteration patterns.
Detection:
typescript
// ❌ PROBLEM - Array creation every frame
{Array(100).fill(0).map((_, i) => (
  <Particle key={i} index={i} />
))}
Solution:
typescript
// ✓ OPTIMIZED - Reuse array reference
const PARTICLES = Array.from({ length: 100 }, (_, i) => i);

{PARTICLES.map((i) => (
  <Particle key={i} index={i} />
))}
Impact: 5-10% improvement in scenes with many elements.
问题: 低效的迭代模式。
检测示例:
typescript
// ❌ 问题 - 每帧创建数组
{Array(100).fill(0).map((_, i) => (
  <Particle key={i} index={i} />
))}
解决方案:
typescript
// ✓ 优化 - 复用数组引用
const PARTICLES = Array.from({ length: 100 }, (_, i) => i);

{PARTICLES.map((i) => (
  <Particle key={i} index={i} />
))}
影响: 包含大量元素的场景性能可提升5-10%。

Performance Optimization Checklist

性能优化检查清单

Computation Optimizations

计算优化

  • No Math.random() in render (use seeded random)
  • Heavy calculations use useMemo
  • Spring calculations extracted and reused
  • Static data moved outside components
  • Loops use Array.from instead of Array().fill()
  • 渲染函数中未使用Math.random()(改用种子随机数)
  • 重型计算使用useMemo
  • spring计算已提取并复用
  • 静态数据已移至组件外部
  • 循环使用Array.from而非Array().fill()

Component Optimizations

组件优化

  • Expensive components wrapped in memo()
  • useMemo for derived state
  • useCallback for event handlers passed to children
  • Components split appropriately (not too large)
  • 重型组件已用memo()包裹
  • 派生状态使用useMemo
  • 传递给子组件的事件处理函数使用useCallback
  • 组件拆分合理(不过于庞大)

Asset Optimizations

资源优化

  • Images sized to actual display dimensions (2x for retina)
  • JPEG for photos, PNG for transparency, SVG for graphics
  • Videos use H.264 codec with reasonable bitrate
  • Audio files trimmed to exact duration
  • Fonts load only required weights
  • 图片尺寸适配实际显示需求(视网膜屏用2倍尺寸)
  • 照片用JPEG、透明图用PNG、图形用SVG
  • 视频使用H.264编码与合理比特率
  • 音频文件裁剪至精确时长
  • 字体仅加载所需字重

Render Optimizations

渲染优化

  • Avoid inline object/array creation in JSX
  • Use key prop correctly in lists
  • Minimize div nesting depth
  • Use CSS transforms over position changes
  • AbsoluteFill instead of complex layouts
  • JSX中避免内联对象/数组创建
  • 列表正确使用key属性
  • 最小化div嵌套深度
  • 使用CSS变换而非位置变更
  • 使用AbsoluteFill替代复杂布局

Architecture Optimizations

架构优化

  • Extract reusable components
  • Scene components under 200 lines
  • Constants extracted to top of file
  • Utility functions outside components
  • Logical component composition
  • 提取可复用组件
  • 场景组件代码不超过200行
  • 常量已提取至文件顶部
  • 工具函数移至组件外部
  • 组件组合逻辑清晰

Performance Benchmarking

性能基准测试

Measuring Render Time

测量渲染时长

bash
undefined
bash
undefined

Benchmark a specific frame

基准测试特定帧

npx remotion still src/index.tsx VideoName --frame=100
npx remotion still src/index.tsx VideoName --frame=100

Benchmark full render (first 100 frames)

基准测试完整渲染(前100帧)

time npx remotion render src/index.tsx VideoName output.mp4 --frames=0-100
time npx remotion render src/index.tsx VideoName output.mp4 --frames=0-100

Profile with Chrome DevTools

使用Chrome DevTools分析

npx remotion preview
npx remotion preview

Open Chrome DevTools → Performance tab → Record

打开Chrome DevTools → Performance标签 → 录制

undefined
undefined

Performance Targets

性能目标

Composition TypeTarget Render TimeNotes
Simple (text, shapes)< 50ms/frameMinimal computations
Moderate (animations, images)50-100ms/frameStandard videos
Complex (particles, 3D)100-200ms/frameHeavy effects
Very Complex (thousands of elements)200-500ms/frameAcceptable with optimization
Red flags:
  • Single frame > 500ms → Major optimization needed
  • Render time increases over time → Memory leak
合成项目类型目标渲染时长说明
简单(文字、图形)< 50ms/帧计算量极小
中等(动画、图片)50-100ms/帧标准视频
复杂(粒子、3D)100-200ms/帧特效密集
极复杂(数千元素)200-500ms/帧经优化后可接受
预警信号:
  • 单帧时长>500ms → 需要重大优化
  • 渲染时长随时间增加 → 存在内存泄漏

Common Bottleneck Patterns

常见瓶颈模式

Pattern 1: Particle Explosion

模式1:粒子爆炸效果

Issue:
typescript
// 1000 particles, each calculating independently
{Array(1000).fill(0).map((_, i) => {
  const x = Math.random() * width;  // Recalculated every frame!
  const y = Math.random() * height;
  return <Particle key={i} x={x} y={y} />;
})}
Fix:
typescript
// Deterministic particles, calculated once
const particles = useMemo(
  () => Array.from({ length: 1000 }, (_, i) => ({
    x: seededRandom(i * 123.456) * width,
    y: seededRandom(i * 789.012) * height,
  })),
  [width, height]
);

{particles.map((p, i) => (
  <Particle key={i} x={p.x} y={p.y} />
))}
问题:
typescript
// 1000个粒子,各自独立计算
{Array(1000).fill(0).map((_, i) => {
  const x = Math.random() * width;  // 每帧重新计算!
  const y = Math.random() * height;
  return <Particle key={i} x={x} y={y} />;
})}
修复方案:
typescript
// 确定性粒子,仅计算一次
const particles = useMemo(
  () => Array.from({ length: 1000 }, (_, i) => ({
    x: seededRandom(i * 123.456) * width,
    y: seededRandom(i * 789.012) * height,
  })),
  [width, height]
);

{particles.map((p, i) => (
  <Particle key={i} x={p.x} y={p.y} />
))}

Pattern 2: Text Processing

模式2:文本处理

Issue:
typescript
// String operations every frame
const words = text.split(' ');
const processed = words.map(w => w.toUpperCase());
Fix:
typescript
// Process once outside render
const processedWords = useMemo(
  () => text.split(' ').map(w => w.toUpperCase()),
  [text]
);
问题:
typescript
// 每帧执行字符串操作
const words = text.split(' ');
const processed = words.map(w => w.toUpperCase());
修复方案:
typescript
// 仅在text变化时处理一次
const processedWords = useMemo(
  () => text.split(' ').map(w => w.toUpperCase()),
  [text]
);

Pattern 3: Conditional Rendering

模式3:条件渲染

Issue:
typescript
// Component always rendered, visibility toggled
<HeavyComponent style={{ opacity: frame > 100 ? 1 : 0 }} />
Fix:
typescript
// Don't render at all when not visible
{frame > 100 && <HeavyComponent />}
问题:
typescript
// 组件始终渲染,仅切换可见性
<HeavyComponent style={{ opacity: frame > 100 ? 1 : 0 }} />
修复方案:
typescript
// 不可见时不渲染
{frame > 100 && <HeavyComponent />}

Optimization Report Template

优化报告模板

markdown
undefined
markdown
undefined

Performance Optimization Report

性能优化报告

Current Performance

当前性能

  • Average render time: 180ms/frame
  • Slowest scene: Scene 3 (350ms/frame)
  • Total video render time: 45 minutes (estimated)
  • 平均渲染时长:180ms/帧
  • 最慢场景:Scene 3(350ms/帧)
  • 预估总视频渲染时长:45分钟

Identified Issues

已识别问题

CRITICAL (Major Impact)
  1. Particle system using Math.random()
    • Location: Scene 2, ParticleSystem component
    • Impact: +200ms per frame
    • Fix: Replace with seeded random
    • Estimated improvement: 55% faster
  2. 4K product image not optimized
    • Location: Scene 4
    • Current: 8.2MB PNG
    • Impact: Slow loading, memory pressure
    • Fix: Resize to 1920x1440, convert to JPEG
    • Estimated improvement: 95% smaller file
HIGH (Significant Impact)
  1. Repeated spring calculations
    • Location: Scene 1, Scene 3, Scene 5
    • Impact: +50ms per scene
    • Fix: Extract to progress variable
    • Estimated improvement: 20% faster
MEDIUM (Moderate Impact)
  1. Components not memoized
    • Location: Scene components
    • Fix: Wrap in React.memo()
    • Estimated improvement: 10% faster
严重(影响重大)
  1. 使用Math.random()的粒子系统
    • 位置:Scene 2,ParticleSystem组件
    • 影响:每帧增加200ms
    • 修复:替换为种子随机数
    • 预估提升:快55%
  2. 未优化的4K产品图片
    • 位置:Scene 4
    • 当前状态:8.2MB PNG
    • 影响:加载缓慢、内存压力大
    • 修复:调整为1920x1440尺寸,转换为JPEG
    • 预估提升:文件缩小95%
高(影响显著)
  1. 重复的spring计算
    • 位置:Scene 1、3、5
    • 影响:每个场景增加50ms
    • 修复:提取为progress变量
    • 预估提升:快20%
中等(影响适中)
  1. 组件未缓存
    • 位置:场景组件
    • 修复:用React.memo()包裹
    • 预估提升:快10%

Optimization Plan

优化计划

  1. Implement seeded random (15 min) — 55% improvement
  2. Optimize assets (30 min) — Better loading
  3. Extract spring calculations (10 min) — 20% improvement
  4. Memoize components (20 min) — 10% improvement
Expected Result:
  • Render time: 180ms → 80ms per frame (55% faster)
  • Total render: 45 min → 20 min
undefined
  1. 实现种子随机数(15分钟)— 提升55%
  2. 优化资源(30分钟)— 加载速度提升
  3. 提取spring计算逻辑(10分钟)— 提升20%
  4. 缓存组件(20分钟)— 提升10%
预期结果:
  • 渲染时长:180ms → 80ms/帧(快55%)
  • 总渲染时长:45分钟 → 20分钟
undefined

Integration with Other Skills

与其他技能的集成

Works with:
  • /remotion-video-reviewer
    — Performance audit during review
  • /remotion-best-practices
    — Ensures optimized patterns
  • /remotion-spec-translator
    — Generates optimized code from start
协同技能:
  • /remotion-video-reviewer
    — 评审过程中的性能审计
  • /remotion-best-practices
    — 确保采用优化后的模式
  • /remotion-spec-translator
    — 从初始阶段生成优化后的代码

Rules Directory

规则目录

Detailed optimization guides:
  • rules/computation-optimization.md — Optimizing calculations
  • rules/asset-optimization.md — Asset size and format
  • rules/memoization-strategies.md — When and how to memoize
  • rules/render-optimization.md — Render path improvements

This skill ensures Remotion videos render as fast as possible while maintaining quality.
详细优化指南:
  • rules/computation-optimization.md — 计算逻辑优化
  • rules/asset-optimization.md — 资源尺寸与格式优化
  • rules/memoization-strategies.md — 缓存的时机与方法
  • rules/render-optimization.md — 渲染路径优化

该技能确保Remotion视频在保持画质的同时,实现最快的渲染速度。