ngStyle 与指令上调用函数之间的性能 [英] Performance between calling function on ngStyle vs directive

查看:27
本文介绍了ngStyle 与指令上调用函数之间的性能的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

<p [ngStyle]="getStyle()"> 
// getStyle returns a string like "color:blue" and some other attributes

<p appStyle [status]="myStatus">
//directive get myStatus as a input and calculate the style of the tag

我正在维护的应用程序在 ngStyle 上多次调用这些函数 getStyle(可能 5k 次).我目前正在将样式计算更改为指令,因为我认为它更干净.

The application that I'm doing maintenance call these functions getStyle on ngStyle a lot (probably 5k times). I am currently changing the style calculation to directives, because I think its cleaner.

但不知道对性能有多大影响.我如何衡量它?

But I don't know how much it will affect performance. How could I measure it?

另一个问题,是否有文档/教程/书籍可以解释这样的事情?

Another question, is there a document/tutorial/book that explain things like that?

谢谢

推荐答案

必须尽量避免属性绑定中的函数调用,这是因为在每个角度变化检测周期都会调用该函数,即使是不相关的属性发生了变化在组件视图上.由于这个原因,绑定到 [ngStyle] 的getStyle()"方法被多次调用 [甚至超过预期].您的第二个代码方法 [指令] 一比功能一要好得多.在指令方法中,当您的有界输入 PROPERTY 发生更改时,只会执行与您的底层指令的输入属性更改相关的代码.您也可以通过使用 ChangeDetectionStrtegy.OnPush [https 来提高性能://blog.angular-university.io/onpush-change-detection-how-it-works/].此外,如果您将数据从数据转换为演示文稿,则应使用 Angular 管道.因为管道被记忆[即仅当输入更改时才评估管道].

A function call in property binding must be avoided as much as possible, this is because the function is called on every angular change detection cycle even an unrelated property is changed on the component view. Because of this reason "getStyle()" method bound to [ngStyle] is called many many times [even more than expected]. Your second code approach [directive] one is far better than function one. In the directive approach when your bounded input PROPERTY is changed then only your underlying directive's input property change related code gets executed. Also you can enhance the performance by using ChangeDetectionStrtegy.OnPush [https://blog.angular-university.io/onpush-change-detection-how-it-works/]. Also, Angular pipe should be used in case you are transforming your data from data to presentation. Because pipes are memoized [i.e. Pipe evaluated only if the input is changed].

请看以下文章-

https://blog.angularindepth.com/tiny-angular-pipe-to-make-any-function-memoizable-f6c8fa917f2fhttps:///blog.angularindepth.com/the-essential-difference-between-pure-and-impure-pipes-and-why-that-matters-999818aa068

这篇关于ngStyle 与指令上调用函数之间的性能的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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