Table of Contents
#1. Why should we optimize
2. In terms of programming habits
3. ChangeDetectionStrategy.OnPush to improve performance
4. Use ngzone-runOutsideAngular to optimize
5. Manually control the dirty check ChangeDetectorRef
6. Summary
Home Web Front-end JS Tutorial A brief discussion on tips for optimizing binding (dirty checking) performance in Angular

A brief discussion on tips for optimizing binding (dirty checking) performance in Angular

Jun 22, 2021 am 10:44 AM
angular

This article will introduce you to Angular performance optimization techniques in binding (dirty checking). It has certain reference value. Friends in need can refer to it. I hope it will be helpful to everyone.

A brief discussion on tips for optimizing binding (dirty checking) performance in Angular

#1. Why should we optimize

Two-way binding is a double-edged sword. While improving development efficiency, it also sacrifices performance. Of course, with the improvement of hardware performance and the improvement of Angular's own performance, for applications of general (small and medium) complexity, performance problems can be ignored. But for special scenarios or complex pages, we need to deal with data binding issues separately, otherwise there will be lags and affect the user experience. [Recommended related tutorials: "angular tutorial"]

2. In terms of programming habits

, some daily tips and habits can be used Improve performance in Angular bindings.

2.1. NgForOf, add trackBy to improve performance

trackBy is a function that defines how to track changes in iterable items. When items are added, moved, or removed from the iterator, the directive must re-render the appropriate DOM node. To minimize churn in the DOM, only nodes that have changed are re-rendered.

By default, the change detector assumes that the object instance identifies the iterable object. When this function is provided, the directive uses the result of calling this function to identify the item node, rather than the identity of the object itself.

2.2. Three ways of Angular data binding

<div>
    <span>Name {{item.name}}</span>  <!-- 1. 直接绑定 -->
    <span>Classes {{item | classPipe}}</span><!-- 2. pipe方式-->
    <span>Classes {{classes(item)}}</span><!-- 3.绑定方法调用的结果 -->
</div>
Copy after login
  • Direct binding: In most cases, These are the best performance methods.

  • The result of the binding method call: During each dirty value detection process, the classes equation must be called once. If there are no special needs, this method of use should be avoided as much as possible.

  • pipe method: It is similar to the binding function. Every time the dirty value detection classPipe is called. However, Angular has optimized the pipe and added caching. If the item is equal to the last time, the result will be returned directly.

<li *ngFor="let item of items; index as i; trackBy: trackByFn">...</li>
Copy after login

2.3. Unless necessary, use one-way binding to reduce the number of monitoring values

For general data, it only needs to be displayed to users and does not need to be modified. Then for this part of the data, just use one-way binding (ts->html).
Such as:

<!-- 也称插值绑定 -->
 <span>{{yourMessage}}</span>
Copy after login

3. ChangeDetectionStrategy.OnPush to improve performance

For some very complex pages, the above tips are not enough, but Angular also takes these into consideration and provides many methods.
Angular Comparison AngularJS changes detection from the original two-way detection (parent->child, child->parent) to one-way (parent->child). So every change detection will converge deterministically.
When Angular defines a component, you can pass in a change detection configuration item as

changeDetection: ChangeDetectionStrategy.OnPush | ChangeDetectionStrategy.Default;
Copy after login

The onpush strategy only determines whether the input reference (if it is an object) has changed to determine whether to perform a dirty check. Therefore, we can use the onpush strategy to reduce the overhead of change detection.

4. Use ngzone-runOutsideAngular to optimize

Angular relies on NgZone to listen for asynchronous operations and perform change detection from the root. In other words, every addEventListener in our code triggers a dirty check. But if we are very clear, some of the things addEventListener needs to execute will not (or can be ignored) affect the data results, otherwise it will trigger a dirty check. For example, monitor scroll, monitor mouse events, etc.

In this case, we can use the runOutsideAngular provided by zone to prevent these events from triggering dirty checks.

this.zone.runOutsideAngular(() => {
    window.document.addEventListener(&#39;mousemove&#39;, this.bindMouse);
});
Copy after login

5. Manually control the dirty check ChangeDetectorRef

Angular's ChangeDetectorRef instance provides a method to bind or unbind the dirty check of a component.

class ChangeDetectorRef {
  markForCheck() : void     // 通知框架进行变化检查/Change Detection
  detach() : void           // 禁止脏检查
  detectChanges() : void    // 手工触发脏检查, 从该组件到各个子组件执行一次变化检测
  checkNoChanges() : void
  reattach() : void         // detach逆操作,启用脏检查
}
Copy after login

6. Summary

  • Some small habits can improve the performance of angular;

  • For complex applications, or when lags occur, we also have solutions!

For more programming-related knowledge, please visit: Programming Teaching! !

The above is the detailed content of A brief discussion on tips for optimizing binding (dirty checking) performance in Angular. For more information, please follow other related articles on the PHP Chinese website!

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

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 ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
WWE 2K25: How To Unlock Everything In MyRise
1 months ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Let's talk about metadata and decorators in Angular Let's talk about metadata and decorators in Angular Feb 28, 2022 am 11:10 AM

This article continues the learning of Angular, takes you to understand the metadata and decorators in Angular, and briefly understands their usage. I hope it will be helpful to everyone!

How to install Angular on Ubuntu 24.04 How to install Angular on Ubuntu 24.04 Mar 23, 2024 pm 12:20 PM

Angular.js is a freely accessible JavaScript platform for creating dynamic applications. It allows you to express various aspects of your application quickly and clearly by extending the syntax of HTML as a template language. Angular.js provides a range of tools to help you write, update and test your code. Additionally, it provides many features such as routing and form management. This guide will discuss how to install Angular on Ubuntu24. First, you need to install Node.js. Node.js is a JavaScript running environment based on the ChromeV8 engine that allows you to run JavaScript code on the server side. To be in Ub

Detailed explanation of angular learning state manager NgRx Detailed explanation of angular learning state manager NgRx May 25, 2022 am 11:01 AM

This article will give you an in-depth understanding of Angular's state manager NgRx and introduce how to use NgRx. I hope it will be helpful to you!

A brief analysis of how to use monaco-editor in angular A brief analysis of how to use monaco-editor in angular Oct 17, 2022 pm 08:04 PM

How to use monaco-editor in angular? The following article records the use of monaco-editor in angular that was used in a recent business. I hope it will be helpful to everyone!

An article exploring server-side rendering (SSR) in Angular An article exploring server-side rendering (SSR) in Angular Dec 27, 2022 pm 07:24 PM

Do you know Angular Universal? It can help the website provide better SEO support!

Angular + NG-ZORRO quickly develop a backend system Angular + NG-ZORRO quickly develop a backend system Apr 21, 2022 am 10:45 AM

This article will share with you an Angular practical experience and learn how to quickly develop a backend system using angualr combined with ng-zorro. I hope it will be helpful to everyone!

How to use PHP and Angular for front-end development How to use PHP and Angular for front-end development May 11, 2023 pm 04:04 PM

With the rapid development of the Internet, front-end development technology is also constantly improving and iterating. PHP and Angular are two technologies widely used in front-end development. PHP is a server-side scripting language that can handle tasks such as processing forms, generating dynamic pages, and managing access permissions. Angular is a JavaScript framework that can be used to develop single-page applications and build componentized web applications. This article will introduce how to use PHP and Angular for front-end development, and how to combine them

A brief analysis of independent components in Angular and see how to use them A brief analysis of independent components in Angular and see how to use them Jun 23, 2022 pm 03:49 PM

This article will take you through the independent components in Angular, how to create an independent component in Angular, and how to import existing modules into the independent component. I hope it will be helpful to you!

See all articles