capacitor-performance

Compare original and translation side by side

🇺🇸

Original

English
🇨🇳

Translation

Chinese

Performance Optimization for Capacitor

Capacitor应用性能优化

Make your Capacitor apps fast and responsive.
让你的Capacitor应用快速且响应流畅。

When to Use This Skill

何时使用本技能

  • User has slow app
  • User wants to optimize
  • User has memory issues
  • User needs profiling
  • User has janky animations
  • 用户的应用运行缓慢
  • 用户想要优化应用性能
  • 用户遇到内存问题
  • 用户需要进行性能分析
  • 用户的动画出现卡顿

Quick Wins

快速优化技巧

1. Lazy Load Plugins

1. 懒加载插件

typescript
// BAD - All plugins loaded at startup
import { Camera } from '@capacitor/camera';
import { Filesystem } from '@capacitor/filesystem';
import { Geolocation } from '@capacitor/geolocation';

// GOOD - Load when needed
async function takePhoto() {
  const { Camera } = await import('@capacitor/camera');
  return Camera.getPhoto({ quality: 90 });
}
typescript
// 错误示例 - 启动时加载所有插件
import { Camera } from '@capacitor/camera';
import { Filesystem } from '@capacitor/filesystem';
import { Geolocation } from '@capacitor/geolocation';

// 正确示例 - 需要时再加载
async function takePhoto() {
  const { Camera } = await import('@capacitor/camera');
  return Camera.getPhoto({ quality: 90 });
}

2. Reduce Bundle Size

2. 缩减包体积

bash
undefined
bash
undefined

Analyze bundle

分析包内容

bunx vite-bundle-visualizer
bunx vite-bundle-visualizer

Tree-shake imports

摇树优化导入

import { specific } from 'large-library'; // Good import * as everything from 'large-library'; // Bad
undefined
import { specific } from 'large-library'; // 正确做法 import * as everything from 'large-library'; // 错误做法
undefined

3. Optimize Images

3. 优化图片

typescript
// Use appropriate quality
const photo = await Camera.getPhoto({
  quality: 80,        // Not 100
  width: 1024,        // Limit size
  resultType: CameraResultType.Uri,  // Not Base64
});

// Lazy load images
<img loading="lazy" src={url} />
typescript
// 使用合适的质量参数
const photo = await Camera.getPhoto({
  quality: 80,        // 不要设为100
  width: 1024,        // 限制图片尺寸
  resultType: CameraResultType.Uri,  // 不要用Base64
});

// 懒加载图片
<img loading="lazy" src={url} />

4. Minimize Bridge Calls

4. 减少原生桥接调用

typescript
// BAD - Multiple bridge calls
for (const item of items) {
  await Storage.set({ key: item.id, value: item.data });
}

// GOOD - Single call with batch
await Storage.set({
  key: 'items',
  value: JSON.stringify(items),
});
typescript
// 错误示例 - 多次桥接调用
for (const item of items) {
  await Storage.set({ key: item.id, value: item.data });
}

// 正确示例 - 批量单次调用
await Storage.set({
  key: 'items',
  value: JSON.stringify(items),
});

Rendering Performance

渲染性能优化

Use CSS Transforms

使用CSS Transform

css
/* GPU accelerated */
.animated {
  transform: translateX(100px);
  will-change: transform;
}

/* Avoid - triggers layout */
.animated {
  left: 100px;
}
css
/* 利用GPU加速 */
.animated {
  transform: translateX(100px);
  will-change: transform;
}

/* 避免使用 - 会触发重排 */
.animated {
  left: 100px;
}

Virtual Scrolling

虚拟滚动

typescript
// Use virtual list for long lists
import { VirtualScroller } from 'your-framework';

<VirtualScroller
  items={items}
  itemHeight={60}
  renderItem={(item) => <ListItem item={item} />}
/>
typescript
// 长列表使用虚拟滚动
import { VirtualScroller } from 'your-framework';

<VirtualScroller
  items={items}
  itemHeight={60}
  renderItem={(item) => <ListItem item={item} />}
/>

Debounce Events

防抖事件

typescript
import { debounce } from 'lodash-es';

const handleScroll = debounce((e) => {
  // Handle scroll
}, 16); // ~60fps
typescript
import { debounce } from 'lodash-es';

const handleScroll = debounce((e) => {
  // 处理滚动事件
}, 16); // 约60fps

Memory Management

内存管理

Cleanup Listeners

清理事件监听器

typescript
import { App } from '@capacitor/app';

// Store listener handle
const handle = await App.addListener('appStateChange', callback);

// Cleanup on unmount
onUnmount(() => {
  handle.remove();
});
typescript
import { App } from '@capacitor/app';

// 保存监听器句柄
const handle = await App.addListener('appStateChange', callback);

// 组件卸载时清理
onUnmount(() => {
  handle.remove();
});

Avoid Memory Leaks

避免内存泄漏

typescript
// Clear large data when done
let largeData = await fetchLargeData();
processData(largeData);
largeData = null; // Allow GC
typescript
// 处理完后清空大型数据
let largeData = await fetchLargeData();
processData(largeData);
largeData = null; // 让垃圾回收器可以回收

Profiling

性能分析

Chrome DevTools

Chrome DevTools

  1. Connect via chrome://inspect
  2. Performance tab > Record
  3. Analyze flame chart
  1. 通过 chrome://inspect 连接设备
  2. 切换到Performance标签页 > 开始录制
  3. 分析火焰图

Xcode Instruments

Xcode Instruments

  1. Product > Profile
  2. Choose Time Profiler
  3. Analyze hot paths
  1. 点击Product > Profile
  2. 选择Time Profiler
  3. 分析热点路径

Android Profiler

Android Profiler

  1. View > Tool Windows > Profiler
  2. Select CPU/Memory/Network
  3. Record and analyze
  1. 点击View > Tool Windows > Profiler
  2. 选择CPU/内存/网络
  3. 录制并分析

Metrics to Track

需跟踪的指标

MetricTarget
First Paint< 1s
Time to Interactive< 3s
Frame Rate60fps
MemoryStable, no growth
Bundle Size< 500KB gzipped
指标目标值
首次绘制时间< 1秒
可交互时间< 3秒
帧率60fps
内存稳定无增长
包体积压缩后 < 500KB

Resources

参考资源