Home > Web Front-end > JS Tutorial > body text

7 tips for performance tuning AngularJS_AngularJS

WBOY
Release: 2016-05-16 15:23:09
Original
1151 people have browsed it

As an excellent web framework, AnglarJS can greatly simplify the burden of front-end development. Recently, Sebastian Fröstl stated in a blog post "AngularJS Performance Tuning for Long Lists" that AnglarJS runs very slowly when processing large lists containing complex data structures. He also shared the solution in the article. Below is a translation of the article.

AnglarJS is great, but it runs very slowly when dealing with large lists containing complex data structures. This is a problem we encountered during the migration of the core admin page to AngularJS. These pages should work smoothly when displaying 500 rows of data, but the first method took an appalling 7 seconds to render.

Later, we discovered that there were two main performance issues during the implementation process. One is related to the "ng-repeat" directive and the other is related to filters.

Below we will share our experience in solving performance problems through different methods, hoping to bring inspiration to you.

 1. Why does ng-repeat in AngularJS slow down when processing large lists?

ng-repeat in AngularJS will slow down when processing more than 2500 two-way data bindings. This is due to AngularJS detecting changes through the "dirty checking" function. Each check takes time, so large lists containing complex data structures will slow down your application.

 2. Prerequisites for improving performance

Time recording command

In order to measure the time it takes to render a list, we wrote a simple program to record the time by using the attribute "$last" of "ng-repeat". The time is stored in the TimeTracker service, so that the time recording is separated from the data loading on the server side.

// Post repeat directive for logging the rendering time angular.module('siApp.services').directive('postRepeatDirective', ['$timeout', '$log', 'TimeTracker', function($timeout, $log, TimeTracker) { return function(scope, element, attrs) { if (scope.$last){ $timeout(function(){ var timeFinishedLoadingList = TimeTracker.reviewListLoaded(); var ref = new Date(timeFinishedLoadingList); var end = new Date(); $log.debug("## DOM rendering list took: " + (end - ref) + " ms"); }); } }; } ]); // Use in HTML: …

Chrome Developer Tools Timeline property

In the Timeline tab of Chrome Developer Tools, you can see events, browser frames per second, and memory allocations. The "memory" tool is used to detect memory leaks and the memory required by pages. The page flickering problem occurs when the frame rate is lower than 30 frames per second. The "frames" tool can help understand rendering performance and can also show the CPU time spent by a JavaScript task.

  3. Basic tuning by limiting the size of the list

The best way to alleviate this problem is to limit the size of the displayed list. This can be achieved by pagination and adding infinite scroll bars.

Pagination

For pagination, we can use AngularJS’s “limitTo” filter (AngularJS version 1.1.4 and later) and “startFrom” filter. You can reduce rendering time by limiting the size of the display list. This is the most efficient way to reduce rendering time.

  // Pagination in controller $scope.currentPage = 0; $scope.pageSize = 75; $scope.numberOfPages = function() { return Math.ceil($scope.displayedItemsList.length/ $scope.pageSize); } ; // Start from filter angular.module('app').filter('startFrom', function() { return function(input, start) { return input.slice(start); }; // Use in HTML // Pagination buttons{{$index + 1}}

If you can’t/don’t want to use paging, but the filtering process is very slow, be sure to check the first five steps and use “ng-show” to hide redundant list elements.

Infinite scroll bar

If you want to know more about this method, you can visit http://binarymuse.github.io/ngInfiniteScroll/

4. Seven tuning rules

 1. Render a list without data binding

This is the most obvious solution since data binding is the most likely source of performance issues. If you only want to display the list once and don't need to update or change the data, giving up data binding is an excellent solution. Unfortunately, you lose control of your data, but we have no choice but to use this law. Learn more: https://github.com/Pasvaz/bindonce.

2. Do not use inline methods to calculate data

To filter the list directly in the controller, do not use methods that get filter links. "ng-repeat" evaluates every [$digest(http://docs.angularjs.org/api/ng.$rootScope.Scope#$digest)%5D expression. In our case, "filteredItems()" returns filtered links. If the evaluation process is slow, it will quickly slow down the entire application.

//This is not a good method because it requires frequent evaluation.

//This is the method to be used

3. Use two lists (one for view display and one as data source)

Separating the list to be displayed from the overall data list is a very useful model. You can preprocess some filters and apply links stored in cache to views. The following case shows the basic implementation process. The filteredLists variable holds the links in the cache, and the applyFilter method handles the mapping.

 /* Controller */ // Basic list var items = [{name:"John", active:true}, {name:"Adam"}, {name:"Chris"}, {name:"Heather" }]; // Init displayedList $scope.displayedItems = items; // Filter Cache var filteredLists['active'] = $filter('filter)(items, {"active" : true}); // Apply the filter $ scope.applyFilter = function(type) { if (filteredLists.hasOwnProperty(type){ // Check if filter is cached $scope.displayedItems = filteredLists[type]; } else { /* Non cached filtering */ } } // Reset filter $scope.resetFilter = function() { $scope.displayedItems = items; } /* View */Select active

 {{item.name}}

 4. Use ng-if in other templates instead of ng-show

If you use instructions or templates to render additional information, such as clicking to display detailed information of a list item, be sure to use ng-if (AngularJSv. 1.1.5 and later). ng-if prevents rendering (compared to ng-show). So other DOM and data bindings can be evaluated as needed.

The above content gives you a detailed explanation of 7 suggestions for performance tuning of AngularJS. I hope you like it.

Related labels:
source:php.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