Performance between calling function on ngStyle vs directive

混江龙づ霸主 提交于 2019-12-13 03:45:54

问题


What is the main difference of

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

to

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

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?

Thanks


回答1:


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].

See the following articles -

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



来源:https://stackoverflow.com/questions/56453858/performance-between-calling-function-on-ngstyle-vs-directive

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