class / 包含很多字段的接口对性能有何影响?

What is the performance impact for a class / interface with a lot of fields?

我的 angular 4 应用程序中有一个 class(界面),它有很多字段。 请注意,此 class/interface 的实例是 immutable(即永远不会更改成员)。

例如

public interface IHaveALotOfFields {
    field1: string;
    //...
    field500: string;
}

此接口是通过(提供的单例/应用程序级别)服务提供的,该服务将 class 作为成员公开。例如

@Injectable()
public class MyService {
    public translations: ITranslationsProvider;
}

该服务被注入到很多组件(几乎所有组件)中,并且经常在它们相应的模板中使用,也经常在组件的 ts 部分中使用。例如。

@Component({
               template: `Value: {{service.field500}}`
           })
export class MyComponent {
    public constructor(public service: MyService) {
    }

    private doSomething(): string {
        return this.service.field1;
    }
}

现在我的问题:

请注意,我不想将所有组件的更改检测策略更改为 OnPush

Will a big class (with a lot of fields) make angular slow because of the change detection?

没有。 Angular 更改检测执行两个读取 class 属性的操作:

  • DOM 更新当前组件
  • 子项的输入绑定更新 components/directives

对于这些操作 Angular 编译器创建了两个函数:

  • updateRenderer - 读取模板中使用的字段
  • updateDirectives - 读取输入绑定表达式中指定的字段

这些函数只读取服务的特定属性。举个例子

Value: {{service.field500}}

updateRenderer 函数看起来像这样:

function(_ck,_v) {
    var _co = _v.component;
    var currVal_0 = _co.service.field500;
    _ck(_v,1,0,currVal_0);

这些函数在每个摘要循环中调用。但是正如您所看到的,只有相关的 属性 将从服务中读取。因此,服务上有多少属性并不重要。

Is there any way to mark a class as "Ignore me on change detection"?

我假设你问的是一次性绑定,就像我们在 AngularJS 中那样。也许它也会添加到 Angular 中。我会监视它并在出现问题时更新答案。但正如您可能知道的那样,您可以 disable/enable 使用 cd.detach/cd.attach 更改组件的检测。您可以监听来自服务的一些信号,并在需要时手动 运行 cd。

以下是您可以阅读以更好地了解变更检测机制的文章列表: