检查属性与检查函数的 return 值相比,性能如何?
What is the performance of checking an attribute vs checking a return value of a function?
我有一个组件中的项目列表:
list: Array<MyType>;
用户可以 select 和 deselect 元素点击:
toggleItem(item: MyType) {
if (this.selection.has(item)) {
this.selection.delete(item);
return;
}
this.selection.add(item);
}
selected 项目存储在 Set
:
selected: Set<MyType> = new Set();
现在我需要切换 CSS class 和 title
属性,具体取决于元素是否 selected:
<button class="toggle"
type="button"
[ngClass]="{'selected': selection.has(item)}"
[title]="selection.has(item) ? 'Select' : 'Deselect'"
(click)="toggleItem(item)">
{{ item.title }}
</button>
现在我在某处读到,评估函数调用是个坏主意,因为 Angular 会定期调用它们进行变化检测,如下所示:
[ngClass]="{'selected': selection.has(item)}"
他们说最好检查变量或对象的成员,例如:
[ngClass]="{'selected': item.selected}"
这是真的,它会降低我目前使用它的方式的性能吗?在 Set
中添加或删除时,我是否应该为每个设置的项目添加 属性?
每当 Angular 执行更改检测时,它都会检查模板中 变量 的任何内容是否已更改。
现在,对于模型变量的检查非常简单,因为 Angular 可以简单地读取它们的值以检查更改。
但函数并非如此。对于函数,Angular只能通过调用函数本身来判断变量是否发生变化。
现在,如果函数是一个 one-liner return 的值,则没有太大区别。
但是如果函数有复杂的逻辑,它基本上会扼杀所有的性能。由于每次更改检测周期运行时,Angular 都会调用该函数以检查并检测更改。
因此,不建议在模板中使用 data-binding 语法编写函数。
NOTE: I've also written a Medium Article about this. I'd suggest you check it out. It's mainly about Angular Reactive Forms performance. But it will help you better understand what I said above.
我有一个组件中的项目列表:
list: Array<MyType>;
用户可以 select 和 deselect 元素点击:
toggleItem(item: MyType) {
if (this.selection.has(item)) {
this.selection.delete(item);
return;
}
this.selection.add(item);
}
selected 项目存储在 Set
:
selected: Set<MyType> = new Set();
现在我需要切换 CSS class 和 title
属性,具体取决于元素是否 selected:
<button class="toggle"
type="button"
[ngClass]="{'selected': selection.has(item)}"
[title]="selection.has(item) ? 'Select' : 'Deselect'"
(click)="toggleItem(item)">
{{ item.title }}
</button>
现在我在某处读到,评估函数调用是个坏主意,因为 Angular 会定期调用它们进行变化检测,如下所示:
[ngClass]="{'selected': selection.has(item)}"
他们说最好检查变量或对象的成员,例如:
[ngClass]="{'selected': item.selected}"
这是真的,它会降低我目前使用它的方式的性能吗?在 Set
中添加或删除时,我是否应该为每个设置的项目添加 属性?
每当 Angular 执行更改检测时,它都会检查模板中 变量 的任何内容是否已更改。
现在,对于模型变量的检查非常简单,因为 Angular 可以简单地读取它们的值以检查更改。
但函数并非如此。对于函数,Angular只能通过调用函数本身来判断变量是否发生变化。
现在,如果函数是一个 one-liner return 的值,则没有太大区别。
但是如果函数有复杂的逻辑,它基本上会扼杀所有的性能。由于每次更改检测周期运行时,Angular 都会调用该函数以检查并检测更改。
因此,不建议在模板中使用 data-binding 语法编写函数。
NOTE: I've also written a Medium Article about this. I'd suggest you check it out. It's mainly about Angular Reactive Forms performance. But it will help you better understand what I said above.