模板中的调用函数是否会导致Angular2 +中的性能问题? [英] Does calling functions in templates cause performance issues in Angular2+?

查看:63
本文介绍了模板中的调用函数是否会导致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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆