在模板中调用函数会导致 Angular2+ 中的性能问题吗? [英] Does calling functions in templates cause performance issues in Angular2+?
问题描述
我还在习惯Angular的变化检测实现,不清楚在模板中调用函数是否会导致性能问题.
I'm still getting used to Angular's change detection implementation, and I'm not clear on whether calling functions in templates causes performance issues.
例如,做以下事情是否更糟:
For example, is it worse to do the following:
<mat-tab-group>
<mat-tab label="First"> {{ getFirstTab() }} </mat-tab>
<mat-tab label="Second"> {{ getSecondTab() }} </mat-tab>
</mat-tab-group>
比做:
<mat-tab-group>
<mat-tab label="First"> {{ firstTabContent }}</mat-tab>
<mat-tab label="Second"> {{ secondTabContent }}</mat-tab>
</mat-tab-group>
关于:
<button *ngIf="shouldShowButton()" .... >
推荐答案
确实如此:当您使用变量时,变更检测会监视该变量,并且更新机制仅在该变量发生变化时触发.
It does: when you use a variable, change detection puts a watch on the variable and the update mechanism fires only when this variable changes.
当您使用更复杂的东西(例如方法调用)时,除了在每个更改检测周期和更新时评估表达式之外别无他法.
When you use something more complicated such as a method call, there is no other way than evaluating the expression at each and every change detection cycle and update.
因此,您始终可以保证使用变量而不是函数调用具有相同或(远远)更好的性能.这完全取决于与变更检测周期的数量相比,您的变量是否发生了很大变化.
Thus, you are always guaranteed to have equal or (much) better performance with a variable rather than a function call. It all depends on wheter your variable changes a lot or not compared to the number of change detection cycles.
您可以在 这篇博文深入了解内部变化检测机制,以及这里有关于您的具体问题的示例讨论.
You can find a nice reference in this blog post to dive in the change detection mechanism internals, and here a discussion with examples on your specific question.
在@enno.void 评论后编辑:
您可以在许多情况下使用自定义管道,示例如下 在此页面上.
You can use a custom pipe instead in many situations, example is given on this page.
这篇关于在模板中调用函数会导致 Angular2+ 中的性能问题吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!