Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How to optimize the performance of Angular change Detection Mechanism

2025-01-27 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)05/31 Report--

This article introduces the knowledge of "how to optimize the performance of Angular change detection mechanism". In the operation of actual cases, many people will encounter such a dilemma, so let the editor lead you to learn how to deal with these situations. I hope you can read it carefully and be able to achieve something!

What is change detection (Change Detection)? Concept of change detection

After the state of the data within the component changes, the view needs to be updated accordingly. This mechanism of synchronizing views with data is called change detection.

Trigger time of change detection

Whenever an asynchronous operation (Events, Timer, XHR) occurs, Angular assumes that a state may have changed, and then changes detection is performed.

Browser events such as Events::click,mouseover,mouseout,keyup,keydown

Timer:setTimeout/setInterval

XHR: all kinds of requests, etc.

Since change detection is performed on asynchronous operations, how does Angular subscribe to asynchronous requests for change detection?

Here's an introduction to NgZone and its fork object, Zone.js.

Zone.js is used to encapsulate and intercept asynchronous activities in browsers. It also provides hooks for asynchronous lifecycles and a unified asynchronous error handling mechanism.

Zone.js uses Monkey Patching (monkey patch) to intercept common methods and elements in browsers, such as setTimeout and HTMLElement.prototype.onclick. Angular patches several low-level browsers API with Zone.js at startup to capture asynchronous events and invoke change detection after the capture time.

Angular extends its own area NgZone through forkZone.js so that all asynchronous operations in the application will run in this area.

How does Angular change detection work?

Angualr generates a change monitor changeDetector for each component to record the change state of the component.

After we have created an Angular application, Angular will also create an instance of ApplicationRef, which represents the instance of the Angular application we currently created. When ApplicationRef is created, it subscribes to the onMicrotaskEmpty event in ngZone and calls detectChanges () of all views to perform change detection after all microtasks are completed.

Change the order in which detection is performed

Update the properties bound by all child components

Call all child component lifecycle hooks OnChanges, OnInit, DoCheck,AfterContentInit

Update the DOM of the current component

Change detection for calling subcomponents

Call the lifecycle hook ngAfterViewInit of all child components

Take Chestnut, for example, we may encounter this kind of error when developing patterns:

This is because change detection follows from the root component, from top to bottom, performing change detection for each component until the last component reaches a steady state. None of the descendant components are allowed to modify the properties in the parent component until the next change detection.

In case 1, in the development mode, Angular will perform a second detection (when enableProdMode () is called in the production environment, the number of tests will be reduced to 1). Once we modify the properties of the parent component in the descendant component after the completion of step 4, the above error occurs when Angular finds that the values are inconsistent twice when performing the second test.

In case 2, as long as the parent component does property binding to the child component, an error will be reported whether the following code is executed in any of the lifecycle hooks in OnChanges,OnInit,DoCheck,AfterContentInit and AfterViewInit.

/ / # parent {{data}} / / in child component ts, execute:this.parent.data = 'new Value'; implementation strategy for change detection

Default strategy

Each time an event triggers change detection (such as user events, timers, XHR, promise, and so on), this default policy checks each component in the component tree from top to bottom. This conservative method of checking component dependencies without making any assumptions is called dirty checking, and this strategy will have an impact on the performance of our applications when we apply too many components.

OnPush strategy

When the changeDetection of the component decorator is modified and set to the OnPush policy, Angular skips change detection for that component and its subcomponents each time it triggers change detection.

Under the OnPush policy, change detection for components is triggered only in the following situations:

DetectChanges (): it triggers change detection for current components and subcomponents

MarkForCheck (): it does not trigger change detection, but marks the current OnPush component and all components whose parent component is OnPush as the state that needs to be detected, which is detected in the current or next change detection cycle

ApplicationRef.tick (): it triggers change detection for the entire application based on the change detection policy of the component

SetTimeout ()

SetInterval ()

Promise.resolve () .then ()

This.http.get ('...'). Subscribe ()

Enter the value (@ Input) to change (the value entered into the input must be a new reference)

The event is triggered by the current component or one of the subcomponents (but in the onPush policy, the following actions do not trigger change detection)

Manually trigger change detection (each component is associated with a component view ChangeDetectorRef)

Async pipe

How to optimize change detection for Angular?

Because the component enforces the Default policy by default, any asynchronous operation triggers a check of the entire number of components from top to bottom. Even if the Angular team continues to improve performance and can complete hundreds of tests in milliseconds, when the application is expanded to hundreds of components, the change detection corresponding to the huge component tree will reach the performance bottleneck.

At this point, we need to start the analysis and reduce the number of unnecessary tests.

How to reduce the number of testing

Regional pollution (Zone Pollution)

Generally, we use a third-party library in the lifecycle hook, such as the chart class library, to initialize it, which comes with requestAnimationRequest/setTimeout/addEventListener. We can write the initialization method into the runOutsideAngular method of NgZone.

OnPush strategy

For views that do not involve update operations, the components can be stripped out and the onPush policy is used to refresh the view by notifying the update (see the Enforcement Policy section of change detection above).

Replace {{function (data)}} with pure pipe

In the html file, the writing of {{function (data)}} causes all values to be recalculated each time change detection occurs. When you have a list of 1000 items, you modify only one piece of data, but the other 999 items that don't need to be updated will be recalculated.)

At this point, we can use the pipe method, only the changed value will trigger the operation and update part of the view.

In the face of rendering a large amount of data, select virtual scrolling / paging to request data

The above 4-point solutions come from the video introduction of the Angular team, in which the number of Angular devtool operations is used to analyze and solve problems. So, if your Angular is 9 minutes, please read on how to install Angular devtool and run it.

Plug-in: introduction to Angular devtool

Angular 9 supports Ivy.

Guide and download address

Ensure that the running environment is the development environment

/ / environment.dev.ts... Production: false...

Angular.json > dev configuration item > "optimization": false

Projects > your-project-name > architect > build > configurations > dev > "optimization": false "how to optimize the performance of Angular change detection mechanism" is introduced here, thank you for reading. If you want to know more about the industry, you can follow the website, the editor will output more high-quality practical articles for you!

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report