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

Methods and steps of Angular optimization

2025-02-24 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/03 Report--

This article mainly explains the "methods and steps of Angular optimization", the content of the explanation is simple and clear, easy to learn and understand, the following please follow the editor's ideas slowly in depth, together to study and learn "Angular optimization methods and steps" bar!

Change detection mechanism

Unlike network transport optimization, runtime optimization focuses more on how Angular works and how to code to effectively avoid performance problems (best practices). To understand how Angular works, you first need to understand its change detection mechanism (also known as dirty checking)-how to re-render state changes to the view. How to reflect the changes of component state into the view is also a problem that the front-end three frameworks need to solve. The solutions of different frameworks have both similar ideas and their own characteristics.

First of all, both Vue and React use virtual DOM to implement view updates, but there are still some differences in implementation:

For React:

Update the view by using the setState or forceUpdate to trigger the render method

When the parent component updates the view, it also determines whether the re-render child component is required.

For Vue:

Vue iterates through all the properties of the data object and uses Object.defineProperty to convert them all to wrapped getter and setter

Each component instance has a corresponding watcher instance object, which records the properties as dependencies during component rendering.

When the dependency's setter is called, the watcher is notified to recalculate so that its associated components can be updated

On the other hand, Angular carries out change detection by introducing Zone.js to patch the API of asynchronous operation and listen for its trigger. The principle of Zone.js was described in detail in a previous article. To put it simply, Zone.js violently encapsulates and replaces all asynchronous API in browsers or Node through Monkey patch (monkey patch).

For example, setTimeout in the browser:

Let originalSetTimeout = window.setTimeout;window.setTimeout = function (callback, delay) {return originalSetTimeout (Zone.current.wrap (callback), delay);} Zone.prototype.wrap = function (callback) {/ / get the current Zone let capturedZone = this; return function () {return capturedZone.runGuarded (callback, this, arguments);};}

Or the Promise.then method:

Let originalPromiseThen = Promise.prototype.then;// NOTE: this is simplified so that then can actually accept more parameters Promise.prototype.then = function (callback) {/ / get the current Zone let capturedZone = Zone.current; function wrappedCallback () {return capturedZone.run (callback, this, arguments);}; / / trigger the original callback in capturedZone return originalPromiseThen.call (this, [wrappedCallback]);}

When Zone.js loads, all asynchronous interfaces are encapsulated. Therefore, all asynchronous methods executed in Zone.js are regulated as a Task, and corresponding hooks functions are provided to do some additional operations before and after the execution of asynchronous tasks or at some stage. Therefore, the functions of logging, monitoring performance and controlling the timing of asynchronous callback execution can be easily realized through Zone.js.

These hook functions (hooks) can be set through the Zone.fork () method. For more information, please see the following configuration:

The type of Zone.current.fork (zoneSpec) / / zoneSpec is ZoneSpec//. Only name is required. Other optional interface ZoneSpec {name: string; / / zone names are generally used to debug Zones using properties?: {[key: string]: any;}; / / some data that zone can attach. OnFork: Function; / / when zone is forked, the function onIntercept?: Function is triggered through Zone.get ('key'). / / intercepting all callbacks onInvoke?: Function; / / when the callback is called, trigger the function onHandleError?: Function; / / A unified handling of exceptions onScheduleTask?: Function; / / when the task is scheduled, trigger the function onInvokeTask?: Function; / / when the task is triggered to execute, trigger the function onCancelTask?: Function; / / trigger the function onHasTask?: Function when the task is cancelled / / notify the status of the task queue to change}

Take a simple column of onInvoke:

Let logZone = Zone.current.fork ({name: 'logZone', onInvoke: function (parentZoneDelegate, currentZone, targetZone, delegate, applyThis, applyArgs, source) {console.log (targetZone.name,' enter'); parentZoneDelegate.invoke (targetZone, delegate, applyThis, applyArgs, source) console.log (targetZone.name, 'leave');}}); logZone.run () {console.log (Zone.current.name,' queue promise') Promise.resolve ('OK') .then ((value) = > {console.log (Zone.current.name,' Promise', value)};})

Final implementation result:

After understanding the principle of Zone.js, by reading the source code of Angular, we can know that Zone.js is used in Angular to trigger change detection whenever an asynchronous method or event is called. It is roughly as follows:

First, in the applicatoin_ref.ts file, the callback event with an empty micro task queue is subscribed to when the ApplicationRef is built, which calls the tick method (that is, change detection):

Second, in the checkStable method, it is determined that the onMicrotaskEmpty event is triggered when the micro-task queue is empty (combined, it is equivalent to triggering change detection):

Finally, the place where the call to the checkStable method can be triggered is in the three hook functions of Zone.js, onInvoke, onInvokeTask, and onHasTask:

For example, onHasTask-- A hook that triggers when a ZoneTask is detected or not:

In addition, asynchronous tasks are divided into three categories in Zone.js:

Micro Task (micro task): created by Promise, etc., the Promise of native is executed before the end of the current event loop, and the patched Promise is also executed before the end of the event loop.

Macro Task (Macro Task): created by setTimeout and others, the setTimeout of native will be processed at some point in the future.

Event Task: created by addEventListener, etc., these task may or may not be triggered multiple times.

In fact, from the browser's point of view, Event Task can actually be regarded as a macro task. In other words, all events or asynchronous API can be understood as one of the macro tasks or micro tasks, and their execution order is analyzed in detail in a previous article. To put it simply:

(1) after the execution of the main thread, priority is given to checking whether there are any tasks in the micro-task queue that need to be executed.

(2) after the first poll, check whether there are any tasks in the macro task queue. After the execution, check whether there are any tasks in the micro task list, and then repeat the process.

Performance optimization principle

Page performance, the most intuitive judgment is to see whether the page response is smooth, whether the response is fast. In essence, the page response is the process of re-rendering the change of the page state to the page. From a relatively macro point of view, Angular change detection is actually only a part of the whole event response cycle. All interactions between the user and the page are triggered by events, and the whole response process is roughly as follows:

If you consider optimizing the speed of page response, you can start with each stage:

(1) for the trigger event phase, the trigger of the event can be reduced to reduce the overall number of change detection and re-rendering.

(2) for the Event Handler execution logic phase, the execution time can be reduced by optimizing the complex code logic.

(3) for the Change Detection detection data binding and update DOM phase, the calculation times of change detection and template data can be reduced to reduce the rendering time.

(4) for the browser rendering phase, you may need to consider using different browsers or upgrading from the hardware configuration

We do not discuss too much about the optimization of phases 2 and 4. Combined with the classification of asynchronous tasks by Angular mentioned above, the optimization methods for phases 1 and 3 can be further clarified:

(1) minimize the number of tick requests for Macro task merge requests

(2) merge tick for Micro task

(3) reduce the trigger and registration events of event for Event task

(4) tick is divided into two stages: check and render, which reduces the calculation of check phase and unnecessary rendering.

As mentioned earlier, in most cases, you can determine whether a page has a performance problem by observing whether the page is smooth or not. Although this approach is simple and intuitive, it is also relatively subjective, not through accurate numbers to reflect the performance of the page. In other words, we need to use a more effective and accurate indicator to measure what kind of page has good performance. The Angular official also provides a corresponding solution, which can be used to monitor the duration of the change detection cycle (completed tick) by turning on the debugging tool of Angular.

First, you need to use the enableDebugTools method provided by Angular, as follows:

Then just type ng.profiler.timeChangeDetection () in the browser's console to see the average change detection time for the current page:

As you can see from the above, the average time to perform 692 change detection cycles (the complete event response cycle) is 0.72 milliseconds. If you run it a few more times, you will find that the total number of runs is different and random.

Officials provide such a criterion: ideally, the length of time printed by the analyzer (the time of a single change detection cycle) should be much lower than that of a single animation frame (16 milliseconds). Generally, this length of time is kept under 3 milliseconds, which means that the performance of the change detection loop of the current page is better. If you exceed this period of time, you can analyze whether there are duplicate template calculations and change detection in conjunction with Angular's change detection mechanism.

Performance optimization scheme

On the basis of understanding the principle of Angular optimization, we can optimize the performance more pertinently:

(1) for asynchronous tasks-reduce the number of change detection

Use the runOutsideAngular method of NgZone to execute the asynchronous interface

Manually trigger change detection for Angular

(2) for Event Task-reduce the number of change detection

Replace events such as input with events that trigger less frequently

Anti-jitter handling of input valueChanges events does not reduce the number of change detection

As shown in the figure above, anti-jitter processing only ensures that the code logic will not run repeatedly, but the event of valueChanges is triggered with the change of value (several times after the change), and change detection will be triggered accordingly as long as the event is triggered.

(3) use Pipe to reduce the number of calculations in change detection

Define pipe as pure pipe (@ Pipe defaults to pure pipe, so you can also set pure: true without display)

Import {Piep, PipeTransform} from'@ angular/core';@Pipe ({name: 'gender', pure,}) export class GenderPiep implements PipeTransform {transform (value: string): string {if (value =' M') return 'male'; if (value ='W') return 'female'; return';}}

About Pure/ImPure Pipe:

Pure Pipe: if the parameter passed into Pipe remains unchanged, the previous calculation result will be returned directly.

ImPure Pipe: each change detection rerun the logic inside Pipe and return the result. (simply put, ImPure Pipe is equivalent to ordinary formattedFunction. If a page triggers change detection multiple times, then the logic of ImPure Pipe will be executed multiple times.)

(4) for components-reducing unnecessary change detection

Component uses onPush mode

The component detects only when the input property changes

Detection is triggered only when the DOM event in the component or its subcomponents is triggered

Other asynchronous events that are not DOM events can only trigger detection manually

The subcomponents of onPush are declared, and if the input properties remain unchanged, they will not be calculated and updated.

@ Component ({... ChangeDetection: ChangeDetectionStrategy.OnPush,}) export class XXXComponent {....}

The changeDetection of @ Component shown in Angular is ChangeDetectionStrategy.OnPush to enable onPush mode (not enabled by default). You can skip the change detection of a component or parent component and all its child components with OnPush, as shown below:

(5) for templates-reducing unnecessary calculation and rendering

Circular rendering of lists using trackBy

Use cached values as much as possible to avoid using method calls and get property calls

If there is indeed a need to call a function in the template, and if there are multiple calls, you can use the template cache.

NgIf controls the display of the component, which is controlled where the component is called.

(6) other coding optimization suggestions

Do not use try/catch for process control, which can cause a lot of time consumption (recording a lot of stack information, etc.)

Too much animation will cause the page to load stutter

Long lists can use virtual scrolling

Delay load for preload module as much as possible, because the concurrency of the browser's http request thread is limited. Once the limit is exceeded, subsequent requests will be blocked and suspended.

Wait

Thank you for your reading, the above is the content of "the methods and steps of Angular optimization". After the study of this article, I believe you have a deeper understanding of the methods and steps of Angular optimization, and the specific use needs to be verified in practice. Here is, the editor will push for you more related knowledge points of the article, welcome to follow!

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