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

查看:83
本文介绍了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管道使任何功能都可记忆的功能f6c8fa917f2f https://blog.angularindepth.com/纯净和不纯净的烟斗和为什么这件事的重要区别-999818aa068

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

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