Home > Web Front-end > JS Tutorial > How to optimize performance in angular? A brief analysis of change detection methods

How to optimize performance in angular? A brief analysis of change detection methods

青灯夜游
Release: 2022-08-31 20:26:13
forward
2542 people have browsed it

angularHow to optimize performance? The following article will give you an in-depth introduction to Angular's performance optimization solution - change detection. I hope it will be helpful to you!

How to optimize performance in angular? A brief analysis of change detection methods

Angular —— —— Change Detection

For the description of the front -end performance indicators, the industry has its own each has its own each. Speaking of words, in summary, it is related to the first screen performance and page fluency. This time, we will analyze page interaction performance optimization from the perspective of page fluency. [Related tutorial recommendations: "angular tutorial

"]

What is page fluency?

Page fluency is determined by the frame rate FPS (Frames Per Second - the number of frames transmitted per second). Generally, the screen refresh rate of mainstream browsers is 60Hz (refreshed 60 times per second). The optimal frame rate is 60 FPS. The higher the frame rate, the smoother the page. 60Hz means that the display screen will be refreshed every 16.6ms, which means that each page rendering needs to be completed within 16.6ms, otherwise the page will be Frame drops and stuttering occur. The root cause is: JavaScript execution and page rendering in the browser block each other

.

In Chrome’s devtools we can execute Cmd Shift P and enter show fps to quickly open the fps panel, as shown below:

How to optimize performance in angular? A brief analysis of change detection methods

By observing the FPS panel , we can easily monitor the fluency of the current page

How to optimize performance in angular? A brief analysis of change detection methods

1 Factors affecting page performance

Whether the page interaction is smooth depends on whether the page response is smooth, and Page response

is essentially the process of re-rendering changes in page status to the page.

The page response process is roughly as follows:

How to optimize performance in angular? A brief analysis of change detection methods

Generally, the Event Handler event processing logic does not consume too much time, so the main factors affecting angular performance areAsynchronous event triggering and change detection

. Generally, the Event Handler event processing logic does not consume too much time, so the factors that affect Angular performance mainly lie in asynchronous event triggering and change detection.

For angular, the process of page rendering is the process of change detection. It can be understood that angular's change detection must be completed within 16.6ms to avoid page frame loss and lag.

The performance of page response can be optimized from the following three aspects.

(1) For the trigger event stage, you can reduce the triggering of asynchronous events

to reduce the overall number of change detections and re-rendering;

(2) For the Event Handler execution logic stage, the execution time can be reduced by optimizing complex code logic;

(3) For the Change Detection detection data binding and updating DOM stage, you canReduce the number of calculations of change detection and template data

to reduce rendering time;

For (2) Event Handler, specific issues need to be analyzed in detail without discussion, mainly for ( 1) (3) Optimize

2 Optimization plan

2.1 Reduce asynchronous event triggering

                                                In Angular’s ​​default change detection mode, asynchronous events will trigger global change detection. Therefore, reducing the triggering of asynchronous events will greatly improve the performance of Angular.

asynchronous event includes Macro Task (macro mission) event and Micro Task micro -task event

How to optimize performance in angular? A brief analysis of change detection methods

This is mainly aimed at Document's monitoring events. For example, listen for click, mouseup, mousemove... and other events on the document.

Listening event scenario:

Renderer2.listen(document,…)

fromEvent(document,…)

document.addEventListener(…)

DOM listening events must be removed when they are no longer needed. ###

Example: [pop] prompt box command

Usage scenario: table column filtering, clicking somewhere other than the icon, or page scrolling, column filtering pop-up box hiding

The previous approach was to directly Monitoring the click event and scroll event of the document in the pop command has the disadvantage that the prompt box is not displayed, but the monitoring event still exists, which is very unreasonable.

Reasonable solution: Only listen to click and scroll events when the prompt box is displayed, and remove the listening events when it is hidden.

How to optimize performance in angular? A brief analysis of change detection methods

For frequently triggered DOM listening events, you can use rjx operators to optimize events. For details, refer to Rjx Operator. RxJS Marbles.

2.2 Change Detection

What is change detection?

To understand change detection, we can find the answer from the goal of change detection. The goal of angular change detection is to keep the model (TypeScript code) and the template (HTML) in sync. Therefore, change detection can be understood as: While detecting model changes, update the template ( DOM ) .

What is the change detection process?

How to optimize performance in angular? A brief analysis of change detection methods

## by performing change detection in the component tree in a

top-down order, that is, performing change detection on the parent component first, and then on the child component Components perform change detection. First check the data changes of the parent component, and then update the parent component template. When updating the template, when encountering the child component, it will update the value bound to the child component, and then enter the child component to see if the index of the @Input input value has changed. If it changes, mark the subcomponent as dirty, which requires subsequent change detection. After marking the subcomponent, continue to update the template behind the subcomponent in the parent component. After all the parent component templates have been updated, make changes to the subcomponent. detection.

2.2.1 Principle of angular change detection

In the default change detection default mode, the principle of asynchronous events triggering Angular's change detection is that angular calls ApplicationRef when processing asynchronous events using Zone.js The tick() method performs change detection from the root component to its child components. During the initialization process of the Angular application, a zone (NgZone) is instantiated, and then all logic is run in the _inner object of the object.

Zone.js implements the following classes:

    Zone class, the execution environment of JavaScript events. Like threads, they can carry some data and may have parent and child zones.
  • ZoneTask class, packaged asynchronous events, these tasks have three subclasses:
  • ##MicroTask, created by Promise.
    • MacroTask, created by setTimeout etc.
    • EventTask, created by addEventListener, etc., such as dom events.
    ZoneSpec object, the parameters provided to it when creating an ngZone, have three hooks that can trigger detection:
  • onInvoke, call an A hook that is triggered when a callback function is called.
    • onInvokeTask, the hook that is triggered when ZoneTask is triggered, such as when setTimeout expires.
    • onHasTask, a hook triggered when detecting the presence or absence of a ZoneTask (that is, triggered for the first schedule zone and the last invoke or cancel task).
    ZoneDelegate class, responsible for calling hooks.
  • The principle of the detection process is roughly as follows:

User operations trigger asynchronous events (for example: DOM events, interface requests...)

=> ZoneTask class handles events. The runTask() method of zone is called in the invokeTask() function. In the runTask method, zone calls the hook of ZoneSpec through the _zoneDelegate instance attribute

=> The three hooks of ZoneSpec (onInvokeTask, onInvoke, onHasTask) In the hook, the zone.onMicrotaskEmpty.emit(null) notification is triggered through the checkStable() function.

=> The root component listens to onMicrotaskEmpty and then calls tick(). The tick method calls

detectChanges()

from The root component starts to detect => ···

refreshView()

Call executeTemplate(), executeTemplate method calls templateFn ()Update template and sub-component binding values ​​(At this time, it will detect whether the sub-component’s @Input() input reference has changed. If there is a change, the sub-component will be marked. is Dirty, that is, the subcomponent requires change detection)Detailed change detection principle flow chart:

How to optimize performance in angular? A brief analysis of change detection methods

Simplify the process:

Trigger asynchronous events

=> ZoneTask handles events

=> ZoneDelegate calls the hook of ZoneSpec Trigger onMicrotaskEmpty notification

=> The root component receives the onMicrotaskEmpty notification, executes tick(), and starts to detect and update the dom

How to optimize performance in angular? A brief analysis of change detection methods

##As can be seen from the above code,

Change detection will be triggered only when the microtask is empty.

Simple change detection principle flow chart:

How to optimize performance in angular? A brief analysis of change detection methods

Angular source code analysis Zone.js reference

blog.

2.2.2 Change detection optimization plan

1) Use OnPush mode

Principle: Reduce the time-consuming of one change detection.

The difference between OnPush mode and Default mode is that DOM listening events, timer events, and promises will not trigger change detection. The component status in Default mode is always CheckAlways, which means that the component must be tested every detection cycle.

In OnPush mode: The following situations will trigger change detection

S1. The @Input reference of the component changes.

S2. Events bound to the component's DOM, including events bound to the DOM of its subcomponents, such as click, submit, mouse down. @HostListener()

Note:

The dom event listened through renderer2.listen() will not trigger change detection

The native listening method through dom.addEventListener() will not trigger change detection Will trigger change detection

S3, Observable subscription event, and set Async pipe at the same time.

S4. Use the following methods to manually trigger change detection:

ChangeDetectorRef.detectChanges(): Trigger change detection of the current component and non-OnPush subcomponents.

ChangeDetectorRef.markForCheck(): Mark the current view and all its ancestors as dirty, and the detection will be triggered in the next detection cycle.

ApplicationRef.tick(): Will not trigger change detection

2) Use NgZone.runOutsideAngular()

Principle: Reduce the number of change detection

Will Global DOM event monitoring is written in the callback of the NgZone.runOutsideAngular() method. DOM events will not trigger Angular's change detection. If the current component has not been updated, you can execute the detectChanges() hook of ChangeDetectorRef in the callback function to manually trigger the change detection of the current component.

Example: app-icon-react dynamic icon component

How to optimize performance in angular? A brief analysis of change detection methods

2.2.3 Debugging method

Method 1: Can be controlled in the browser Taiwan, use the Angular DevTools plug-in to view a certain DOM event, angular detection:

1How to optimize performance in angular? A brief analysis of change detection methods## Method 2: You can directly enter: ng.profiler.timeChangeDetection() in the console to view Detection time, this way you can view the global detection time. Reference blog

Profiling Angular Change Detection

1How to optimize performance in angular? A brief analysis of change detection methods

2.3 Template (HTML) optimization

2.3.1 Reduce DOM Rendering: ngFor plus trackBy

Using the trackBy attribute of *ngFor, Angular only changes and re-renders the changed entries without having to reload the entire list of entries.

For example: table sorting scenario. If trackBy is added to ngFor, only the row dom elements will be moved when the table is rendered. If trackBy is not added, the existing table dom elements will be deleted first, and then the row dom elements will be added. Obviously the performance of moving only dom elements will be much better.

2.3.2 Do not use functions in template expressions

Do not use function calls in Angular template expressions. You can use a pipe instead, or you can use a variable after manual calculation. When functions are used in templates, regardless of whether the value has changed or not, the function will be executed every time change detection is performed, which will affect performance.

Scenarios for using functions in templates:

1How to optimize performance in angular? A brief analysis of change detection methods

2.3.3 Reduce the use of ngFor

Using ngFor will affect performance when the amount of data is large.

Example:

Use ngFor:

1How to optimize performance in angular? A brief analysis of change detection methods

1How to optimize performance in angular? A brief analysis of change detection methods

##Not using ngFor: performance increased by about 10 times

1How to optimize performance in angular? A brief analysis of change detection methods

1How to optimize performance in angular? A brief analysis of change detection methods

For more programming-related knowledge, please visit:

Programming Video! !

The above is the detailed content of How to optimize performance in angular? A brief analysis of change detection methods. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:juejin.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template