capacitor-performance
Compare original and translation side by side
🇺🇸
Original
English🇨🇳
Translation
ChinesePerformance 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
undefinedbash
undefinedAnalyze 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
undefinedimport { specific } from 'large-library'; // 正确做法
import * as everything from 'large-library'; // 错误做法
undefined3. 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); // ~60fpstypescript
import { debounce } from 'lodash-es';
const handleScroll = debounce((e) => {
// 处理滚动事件
}, 16); // 约60fpsMemory 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 GCtypescript
// 处理完后清空大型数据
let largeData = await fetchLargeData();
processData(largeData);
largeData = null; // 让垃圾回收器可以回收Profiling
性能分析
Chrome DevTools
Chrome DevTools
- Connect via chrome://inspect
- Performance tab > Record
- Analyze flame chart
- 通过 chrome://inspect 连接设备
- 切换到Performance标签页 > 开始录制
- 分析火焰图
Xcode Instruments
Xcode Instruments
- Product > Profile
- Choose Time Profiler
- Analyze hot paths
- 点击Product > Profile
- 选择Time Profiler
- 分析热点路径
Android Profiler
Android Profiler
- View > Tool Windows > Profiler
- Select CPU/Memory/Network
- Record and analyze
- 点击View > Tool Windows > Profiler
- 选择CPU/内存/网络
- 录制并分析
Metrics to Track
需跟踪的指标
| Metric | Target |
|---|---|
| First Paint | < 1s |
| Time to Interactive | < 3s |
| Frame Rate | 60fps |
| Memory | Stable, no growth |
| Bundle Size | < 500KB gzipped |
| 指标 | 目标值 |
|---|---|
| 首次绘制时间 | < 1秒 |
| 可交互时间 | < 3秒 |
| 帧率 | 60fps |
| 内存 | 稳定无增长 |
| 包体积 | 压缩后 < 500KB |
Resources
参考资源
- Chrome DevTools: https://developer.chrome.com/docs/devtools
- Xcode Instruments: https://developer.apple.com/instruments
- Chrome DevTools: https://developer.chrome.com/docs/devtools
- Xcode Instruments: https://developer.apple.com/instruments