简体   繁体   中英

Calling function from view in angularJS = bad performance?

I've noticed that if I call functions from my angular view, the functions are called a lot. Also when the data hasn't changed.

For example:

<div ng-repeat="day in days_array">
   {{getWeek(day)}}
</div>

Then getWeek() gets called for all the items in days_array every time almost anything in the application changes. So I wondered if this is what filters are solving? So filters are only called when days_array is actually changed, and therefore gives better performance?

Would not be easier to optimize to map week once and use it directly in HTML? In some place you load days:

$scope.loadDays = function () {
    service.getDays().then(function (days_array) {
        $scope.days_array = days_array.
    });
}

Or you have it hard-coded:

$scope.days_array = [{index: 0, code: MONDAY}...];

You can easily add week property:

$scope.days_array = $scope.days_array.map(function (day) {
    day.week = getWeek(day);
    return day;
});

And use it in HTML like this:

<div ng-repeat="day in days_array">
   {{day.week}}
</div>

And it performs as usual Angular binding. Moreover, you can optimize it further - if week never changes you can use one-time binding:

<div ng-repeat="day in days_array">
   {{::day.week}}
</div>

Angular forgets about checking this variable. And even one more step - if days_array is set once and never changes, you can forget about list at all:

<div ng-repeat="day in ::days_array">
   {{::day.week}}
</div> 

Yes it's bad performance. Filters would help, yes. If you can have a way when something is added to know if it's newly added.

I will leave this link with performance tips on angularjs loops

https://codeutopia.net/blog/2014/11/10/angularjs-best-practices-avoid-using-ng-repeats-index/

I hope it helps.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM