Does calling functions in templates cause performance issues in Angular2+?

穿精又带淫゛_ 提交于 2019-12-11 04:49:25

问题


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>

than do:

<mat-tab-group>
  <mat-tab label="First"> {{ firstTabContent }}</mat-tab>
  <mat-tab label="Second"> {{ secondTabContent }}</mat-tab>
</mat-tab-group>

What about:

<button *ngIf="shouldShowButton()" .... >   

回答1:


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.

Edit after @enno.void comment:

You can use a custom pipe instead in many situations, example is given on this page.




回答2:


the first method is possible as long as you are calling string...and the function should be inside the mat-tab like this:

<mat-tab-group>
  <mat-tab label="First" {{ getFirstTab() }}> </mat-tab>
  <mat-tab label="Second" {{ getSecondTab() }}> </mat-tab>
</mat-tab-group> 

i don't think the last one will even work at all...calling a function in *ngIf will give error

<button *ngIf="shouldShowButton()" .... > 


来源:https://stackoverflow.com/questions/55632704/does-calling-functions-in-templates-cause-performance-issues-in-angular2

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!