Ember性能优化 #

一、性能优化概述 #

1.1 优化目标 #

目标 说明
加载时间 减少初始加载时间
运行性能 提高渲染效率
内存使用 减少内存占用
包体积 减小代码体积

1.2 性能指标 #

  • First Contentful Paint (FCP)
  • Largest Contentful Paint (LCP)
  • Time to Interactive (TTI)
  • Total Blocking Time (TBT)

二、代码分割 #

2.1 路由懒加载 #

javascript
// app/router.js
Router.map(function () {
  this.route('admin', function () {
    this.route('dashboard', { path: '/' });
    this.route('users');
  });
});

2.2 组件懒加载 #

javascript
import Component from '@glimmer/component';
import { tracked } from '@glimmer/tracking';

export default class LazyComponent extends Component {
  @tracked loaded = false;
  @tracked component = null;

  async loadComponent() {
    const { default: HeavyComponent } = await import('./heavy-component');
    this.component = HeavyComponent;
    this.loaded = true;
  }
}

三、模板优化 #

3.1 减少追踪范围 #

javascript
// 好的做法 - 细粒度追踪
class Person {
  @tracked firstName = '';
  @tracked lastName = '';
}

// 避免 - 粗粒度追踪
class Person {
  @tracked data = { firstName: '', lastName: '' };
}

3.2 使用let缓存 #

handlebars
{{#let (expensive-computation @data) as |result|}}
  <p>{{result}}</p>
  <p>{{result}}</p>
{{/let}}

四、数据优化 #

4.1 预加载关联 #

javascript
model(params) {
  return this.store.findRecord('post', params.id, {
    include: 'author,comments',
  });
}

4.2 分页加载 #

javascript
model() {
  return this.store.query('post', {
    page: 1,
    limit: 20,
  });
}

五、构建优化 #

5.1 生产构建 #

bash
ember build --environment=production

5.2 分析包体积 #

bash
ember build --environment=production
npx source-map-explorer dist/assets/my-app.js

六、总结 #

性能优化要点:

技术 用途
懒加载 按需加载
代码分割 减小包体积
预加载 加速关联访问
缓存 减少重复计算

性能优化是持续改进的过程。

最后更新:2026-03-28