search
HomeWeb Front-endJS TutorialHow to optimize performance in angular? A brief analysis of change detection methods

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!

Statement
This article is reproduced at:掘金社区. If there is any infringement, please contact admin@php.cn delete
Python vs. JavaScript: The Learning Curve and Ease of UsePython vs. JavaScript: The Learning Curve and Ease of UseApr 16, 2025 am 12:12 AM

Python is more suitable for beginners, with a smooth learning curve and concise syntax; JavaScript is suitable for front-end development, with a steep learning curve and flexible syntax. 1. Python syntax is intuitive and suitable for data science and back-end development. 2. JavaScript is flexible and widely used in front-end and server-side programming.

Python vs. JavaScript: Community, Libraries, and ResourcesPython vs. JavaScript: Community, Libraries, and ResourcesApr 15, 2025 am 12:16 AM

Python and JavaScript have their own advantages and disadvantages in terms of community, libraries and resources. 1) The Python community is friendly and suitable for beginners, but the front-end development resources are not as rich as JavaScript. 2) Python is powerful in data science and machine learning libraries, while JavaScript is better in front-end development libraries and frameworks. 3) Both have rich learning resources, but Python is suitable for starting with official documents, while JavaScript is better with MDNWebDocs. The choice should be based on project needs and personal interests.

From C/C   to JavaScript: How It All WorksFrom C/C to JavaScript: How It All WorksApr 14, 2025 am 12:05 AM

The shift from C/C to JavaScript requires adapting to dynamic typing, garbage collection and asynchronous programming. 1) C/C is a statically typed language that requires manual memory management, while JavaScript is dynamically typed and garbage collection is automatically processed. 2) C/C needs to be compiled into machine code, while JavaScript is an interpreted language. 3) JavaScript introduces concepts such as closures, prototype chains and Promise, which enhances flexibility and asynchronous programming capabilities.

JavaScript Engines: Comparing ImplementationsJavaScript Engines: Comparing ImplementationsApr 13, 2025 am 12:05 AM

Different JavaScript engines have different effects when parsing and executing JavaScript code, because the implementation principles and optimization strategies of each engine differ. 1. Lexical analysis: convert source code into lexical unit. 2. Grammar analysis: Generate an abstract syntax tree. 3. Optimization and compilation: Generate machine code through the JIT compiler. 4. Execute: Run the machine code. V8 engine optimizes through instant compilation and hidden class, SpiderMonkey uses a type inference system, resulting in different performance performance on the same code.

Beyond the Browser: JavaScript in the Real WorldBeyond the Browser: JavaScript in the Real WorldApr 12, 2025 am 12:06 AM

JavaScript's applications in the real world include server-side programming, mobile application development and Internet of Things control: 1. Server-side programming is realized through Node.js, suitable for high concurrent request processing. 2. Mobile application development is carried out through ReactNative and supports cross-platform deployment. 3. Used for IoT device control through Johnny-Five library, suitable for hardware interaction.

Building a Multi-Tenant SaaS Application with Next.js (Backend Integration)Building a Multi-Tenant SaaS Application with Next.js (Backend Integration)Apr 11, 2025 am 08:23 AM

I built a functional multi-tenant SaaS application (an EdTech app) with your everyday tech tool and you can do the same. First, what’s a multi-tenant SaaS application? Multi-tenant SaaS applications let you serve multiple customers from a sing

How to Build a Multi-Tenant SaaS Application with Next.js (Frontend Integration)How to Build a Multi-Tenant SaaS Application with Next.js (Frontend Integration)Apr 11, 2025 am 08:22 AM

This article demonstrates frontend integration with a backend secured by Permit, building a functional EdTech SaaS application using Next.js. The frontend fetches user permissions to control UI visibility and ensures API requests adhere to role-base

JavaScript: Exploring the Versatility of a Web LanguageJavaScript: Exploring the Versatility of a Web LanguageApr 11, 2025 am 12:01 AM

JavaScript is the core language of modern web development and is widely used for its diversity and flexibility. 1) Front-end development: build dynamic web pages and single-page applications through DOM operations and modern frameworks (such as React, Vue.js, Angular). 2) Server-side development: Node.js uses a non-blocking I/O model to handle high concurrency and real-time applications. 3) Mobile and desktop application development: cross-platform development is realized through ReactNative and Electron to improve development efficiency.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Chat Commands and How to Use Them
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

MinGW - Minimalist GNU for Windows

MinGW - Minimalist GNU for Windows

This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

Atom editor mac version download

Atom editor mac version download

The most popular open source editor