Comparison of performance between custom filter and filter function in the controller

Imagine having an array containing 5000 objects with boolean values that need to be displayed using ng-repeat in the template:

$scope.arr = [
    {
        "value": true
    },
    {
        "value": false
    },
    {
        "value": false
    }
    //and so on
]

The goal is to filter this array based on a dynamic variable called 'show_filter' which is set elsewhere.

If 'show_filter' is set to 'all', all objects should be displayed. If it is set to false, only objects with 'value' key set to false should be shown. The same applies when 'show_filter' is set to true.

There are two possible approaches for achieving this task:

1. Implementation of a custom filter:

A custom filter can be created for this purpose as follows:

filter:

app.filter('filterArr', function() {
    return function(arr, show_filter) {
        var filtered_arr = [];
        if(show_filter != 'All') { 
            for(var i = 0; i < arr.length; i++) {
                if(arr[i].value == show_filter) { 
                    filtered_arr.push(arr[i]);
                }
            }
            return filtered_arr;
        }
        else {
            return arr;
        }
    }
})

template:

obj in arr | filterArr : show_filter

2. Creating a filter function in the controller:

filter:

$scope.filterObjects = function(arr) {
    var filtered_arr = [];
    if($scope.show_filter != 'All') { 
        for(var i = 0; i < arr.length; i++) {
            if(arr[i].value == $scope.show_filter) { 
                filtered_arr.push(arr[i]);
            }
        }
        return filtered_arr;
    }
    else {
        return arr;
    }
}

template:

obj in filterObjects(arr)

Which of these methods is more efficient? There seems to be a concern about the custom filter executing for each digest loop rather than just for changes in $scope.show_filter, which may indicate inefficiency. It is unclear which method is faster between the two options presented.

Answer №1

Both functions will run during each digest cycle. The second function's behavior in this regard is quite clear. However, the outcome of filterObjects(arr) may vary with each call.

The reason why a filter is invoked in every digest cycle might not be immediately evident. According to the documentation:

The filter function should be pure, meaning it should be stateless and idempotent. Angular depends on these characteristics and only triggers the filter when its inputs change.

Therefore, unless arr or show_filter changes, the filter should theoretically not be executed. However, the process of detecting changes in arr can be resource-intensive.

Angular needs to create a copy of the array for comparison against the current content. Even if no modifications are made, every item within needs to be inspected. When dealing with object items, every property of each object must also be scrutinized. Consequently, directly calling a filter proves to be a more efficient alternative. This is precisely what Angular does when applying a filter to an array (or object).

To optimize performance, you have two options. Firstly, filter the array as needed and expose the filtered array to ng-repeat. For instance, if filtering occurs based on a specific value input, update the array whenever that value changes.

The second approach, applicable when both the array and filter remain constant (not in your scenario), involves utilizing one-time binding:

<li ng-repeat="item in ::array | filter">

This method is beneficial when working with a predetermined set of items,such as sorting by name. In such cases, the filter is executed just once.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Concealing tables with Jquery during PostBack in ASP.net

There have been some discussions about this, but I'm struggling to connect all the pieces. My question is related to dynamic tables for which I've created CSS classes. I use checkboxes and jQuery to hide different tables... However, after a postb ...

What are some strategies for handling analytics tracking in Flux architecture?

Imagine I'm working on a cutting-edge single page application similar to Airbnb. One essential aspect of such an application is keeping track of when someone signs up for an account. There are numerous services available to assist with tracking, incl ...

Dynamic sliding form using jquery and javascript

Currently, I am in the process of developing a survey website that presents questions one by one. Upon selecting an answer and submitting it, the current page will smoothly transition to the next question. I have been exploring methods to achieve this fun ...

In comparison to InnoDB, MySQL Cluster exhibits significantly lower performance speeds

I am facing an issue with my denormalized table called product which contains approximately 6 million rows (~ 2GB) used mainly for lookups. The fields in this table include price, color, unitprice, weight, ... I have implemented BTREE indexes on fields li ...

Retrieving the caret's position in TinyMCE 4

Is there a way to retrieve the caret position in pixels (x & y dimensions) in TinyMCE 4 without obtaining row/column numbers? It should be relative to anything and achieved without adding any extra tags like bookmarks. Anyone know if TinyMCE has a method f ...

Guide on translating a date object with angular-translate

I am currently facing a challenge with localizing date objects in my Angular application. I have a list of dates displayed in my view, powered by the controller. I am using angular-translate for managing localization throughout the application, but I' ...

Vue.js not firing onclick event

Here is a code snippet for a Vue.js template: <script type="text/x-template" id="ti-page-inquire"> <div> <h3 class="mdc-typography--headline3">{{page.name}}</h3> <ti-button v-bind:button="page.button" v-on:cl ...

JavaScript's getElementsByName() method allows for easy access and

Excuse my lack of experience... I am attempting to run a javascript using the getElementByName method, with the goal of entering 0 in the quantity field on a particular site after 15 seconds of arriving there. Upon inspecting the quantity field, here is w ...

Incorporating password protection into in-place editing within Angular.js

Check out my example here I am looking to implement password protection when the "Edit title" button is clicked. Any suggestions on how I can achieve this? Here is the JS code snippet: function ClickToEditCtrl($scope) { $scope.title = "Welcome to thi ...

When the window is scrolled to 50%, I would like to load some additional data

Looking to load data when the browser scrollbar reaches 50%... In jQuery, I created the following function: $(window).on('scroll', function () { alert("scrolling"); if ($(window).scrollTop() + $(window).innerHeight() > ...

Creating a table header that displays the next and previous days using JavaScript

I am currently working on creating a dynamic HTML header using JavaScript to display all week days with dates for the upcoming and previous weeks. When a button is clicked for the next week, the table header should change from this week to next week; simil ...

Effortlessly sending multiple values from text fields using jQuery

i am using jQuery to fetch all values from text fields with the same field name. $('input[name^="StudentName"]').each(function() { StudentName += $(this).val(); alert(StudentName); }); when I alert, all the values are displayed as one s ...

The error message "bootstrapDialog is encountering issues due to a problem with querySelector function"

I encountered an error while using bootstrapDialog. Specifically, when I tried to initialize the dialog with BootstrapDialog.alert('I want banana!'); Is there anyone who can assist me in resolving this issue? The browser displayed the following ...

Express server having issues with AngularJS integration

Currently delving into the world of AngularJS and experimenting with some basic examples. Successfully installed Node and utilized npm to incorporate express in the designated directory for my projects. Following a straightforward example to display an htm ...

Can I use react-image-crop to resize an image on the web?

I am wondering if it's possible to use the npm package react-image-crop to crop an image that is hosted online rather than locally stored on my computer. I know how to crop local images, but I'm curious about cropping images using their URL. Is t ...

When making a request with XMLHttpRequest(), FormData() is not being sent, causing the PHP $_FILES array to be empty and the

My Objective: I am attempting to achieve the task of uploading a file from a user to a specific directory on the server using an HTML <input type="file"> element. To accomplish this, I have implemented a new XMLHttpRequest within the <input> ...

Tips for transferring parameters between AJAX requests

Struggling to pass parameters between two different ajax calls, I've noticed that the params only exist within the ajax scope and not outside of it. Is there another way to achieve this without calling from one ajax success section to another ajax? He ...

Elevate javascript

How can I create a new constructor that will alert the increment value? Any suggestions on how to achieve this? This is the current code snippet: var increment = new Increment(); alert(increment); /* 1 */ alert(increment); /* 2 */ alert(increment + incr ...

Unable to install the Cordova barcode scanner plugin due to an error: "SyntaxError: Unexpected token =>"

Attempting to install the plugin at this link: https://github.com/phonegap/phonegap-plugin-barcodescanner but encountering the following error message: SyntaxError: Unexpected token => at exports.runInThisContext (vm.js:73:16) at Module._compile (modul ...

The sluggishness of the comment system is attributed to the intricate layers

A new photo viewing and commenting system has been developed, allowing users to interact with albums. When a user clicks on an album, they are directed to a page where the first photo, along with comments and replies, is displayed in the center. All other ...