What makes using for faster than some() or filter()?

After experimenting with two different approaches, I was taken aback by the performance results:

I have implemented 2 versions of a function :

First Method using a for loop :

$scope.hasBlockResult = function (IS, area, block) {
    if (!block)
        return false;
    for (var i = 0; i < $scope.filteredCartoList.length; i++) {
        if ($scope.filteredCartoList[i].informationSystem === IS 
            && $scope.filteredCartoList[i].area === area 
            && $scope.filteredCartoList[i].block === block)
            return true;
    }
    return false;
};

Second Method using some() function :

$scope.hasBlockResult = function (IS, area, block) {
    if (!block)
        return false;

    return ($scope.filteredCartoList.some(function (carto) {
        if (carto.informationSystem === IS && carto.area === area && carto.block === block)
            return true;
        return false;
    }));
};

Similar scenario here :

Comparing the for loop :

for (var i = 0; i < $scope.filteredCartoList.length; i++) {
    if ($scope.filteredCartoList[i].informationSystem == IS 
        && $scope.filteredCartoList[i].type != 'AM' 
        && $scope.filteredCartoList[i].type != 'IF' 
        && $scope.filteredCartoList[i].area == area 
        && $scope.filteredCartoList[i].block == block)
        $scope.resultList.push($scope.filteredCartoList[i]);
    }

and the filter() method :

$scope.resultList = $scope.filteredCartoList.filter(function (carto) {
    if (carto.informationSystem == IS 
        && carto.type != 'AM' 
        && carto.type != 'IF' 
        && carto.area == area 
        && carto.block == block)
        return true;
    return false;
});

I anticipated that the filter() and some() methods would outperform the for loop, but surprisingly, according to angularjs batarang's performance tab, the for loop turned out to be faster.

Answer №1

After reviewing the benchmarks shared in the comments through this link, it's clear that there are some flaws present in these tests:

  • The loop example includes operations like console.timeEnd and console.log within the benchmark itself, which can introduce slowdowns compared to other examples.
  • In the some example, type coercion is performed, potentially affecting the results.
  • All tests involve string concatenation within their loops, impacting performance.

To derive meaningful insights from these benchmarks, it's crucial to address these sources of bias first.

Below are the adjusted results on an 8GB DDR3 i5 Laptop after eliminating these biases, presented from fastest to slowest (lower values indicate better performance):

OBJECT Average 0.0010666643114139636
SEEK Average 0.00593666957380871
LOOP Average 0.008436664550875625
SOME Average 0.013993332007279
FILTER Average 0.02592999837361276

These outcomes align with expectations, as explained below:

Object Access

Accessing objects is fast due to their nature as hash maps, ensuring constant speed regardless of object size.

Seek

The seek operation involves locating an element using indexOf and accessing it directly via array index. This method closely resembles object access, resulting in swift performance.

Loop

The loop approach, unlike 'seek', requires iterating over the entire array and combining both array and object access. This additional step contributes to its slower execution compared to the seek test.

Hence, under most circumstances, seek will outperform loop.

Some

The 'some' test incurs overhead from invoking a function during each iteration. Additionally, JIT compiler optimizations are limited due to variable inputs, making 'some' generally slower than 'loop' even at its best performance levels.

Filter

Similar to 'some', 'filter' faces the challenges of function invocations and processing the entire array without early termination. Moreover, the creation of a new array by filter adds further overhead, highlighting its inherent slowness compared to traditional for loops.

Answer №2

When it comes to performance, nothing can beat using native (vanilla) javascript. The question essentially boils down to whether you want to invest time and resources into reinventing the wheel by coding everything from scratch, or if you prefer to utilize an external library that can do the heavy lifting for you. While using an external library may impact load time and overall performance, it ultimately saves you valuable time - and as they say, time is money. One way to optimize your code further is to cache the length of an array in a for loop like this:

for (var i = 0, len = $scope.filteredCartoList.length; i < len; i++)

This approach can significantly improve speed, especially in browsers like Internet Explorer, by storing the length of $scope.filteredCartoList instead of recalculating it with every iteration of the loop.

Answer №3

Consider these contrasting examples:

for (var i = 0; i < list.length; i++) {
    doAction(list[i]);
}

vs.

function processItem(item) {
    doAction(item);
}
for (var i = 0; i < list.length; i++) {
    processItem(list[i]);
}

Essentially, this illustrates the difference between the two approaches. In addition to this, there needs to be specific handling within filter and some functions to deal with the output of processItem, but fundamentally, an extra function call is being added on top of the looping mechanism.

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

Avoiding the duplication of selected items in a dropdown within a gridview can be achieved effectively by implementing a JavaScript/jQuery

In my gridview, which contains multiple rows, each row has a dropdown (select in HTML). My goal is to prevent the user from selecting the same item from the dropdown list for different rows. For instance, if a user selects "New York": Assigning rooms: U ...

How does node.js enhance the functionality of Protractor?

As a newcomer to AngularJS, I am diving into automating an AngularJS application. I have successfully installed node.js and protractor (npm install -g protractor) I then updated the webdriver manager tool (webdriver-manager update) and started the drive ...

What could be causing the Error when using the then() callback in ExpressJS following a promise?

Trying to figure out NodeJS and ExpressJS, attempting a basic Database query. db.execute('SELECT * FROM restaurant').then().catch() An error is popping up : db.execute('SELECT * FROM restaurant').then().catch() ...

Exploring the Uses of JQuery Functions

The functions below are working as expected, but when I try to include the custom functions next() and prev(), something is off with the script. Where could the issue be stemming from? function next() { $('#up').click(function() { ...

Automatically open the first panel of the Jquery Accordion

Is there a way to automatically have the first panel in my JQuery accordion open when all panels are initially closed? Here is the HTML code for my accordion: <div class="accordionx"> <div class="acitemx"> <h3>First Panel</h3> ...

When working with Mongoose and TypeScript, encountering the 'connect' error from mongoose can be frustrating and disruptive to your

After attempting to start the server, an error message is displayed: this.mongo.connect('mongodb://localhost:27017/tsnode', { ^ TypeError: Cannot read property 'connect' of undefined import express from 'express&ap ...

There was an error in the syntax: an expression was expected, but instead the character '}' was found in mongoDB

Encountering the error message SyntaxError: expected expression, got '}' @(shell):1:0 when executing a query in the shell. db.address.aggregate([ { "$project": { "applications": { "$filter": { ...

What are the steps for implementing function composition or pipelines with a multi-parameter function?

During a recent interview, I was tasked with retrieving data from the jsonplaceholder /posts and /comments endpoints and creating a function to match comments with posts where comment.postId == post.id, then constructing a unified JSON object containing ea ...

How to transform a JSON object into an array using JavaScript

Is there a way to convert a JSON key value object into an Array that is easier to iterate through? The JSON I have looks something like this: { "01": "yes", "02": "yes", "03": "no" } However, I need the Array format below in order to easily iterate ...

Modify the nested object's two layers using the designated ID

In my Mother Model, there is a fixed structure where I manipulate cards on three array levels: starter, intermediate, and advanced. { cards: { starter: [], intermediate: [], advanced: [ {Object}, {Object}, {Object} ] }, } The objects withi ...

Creating dynamic scroll animations for sidebar navigation in a single-page website with anchor links

I need help creating a seamless transition between anchor points on a single page, while keeping a fixed navigation menu that highlights the active section. As a novice, I am unsure how to incorporate "( document.body ).animate" or any other necessary code ...

Storing user credentials in Firestore after registration - best practices

Hi, I need some assistance with storing user credentials in Firestore after they sign up. Unfortunately, I keep encountering the following error: Invalid collection reference. Collection references must have an odd number of segments, but userDatabase/QMJ ...

deck.gl TripLayer showcases individual route mapping

I am interested in using Deck.gl to visualize trip data. I have successfully tested running local data with the example dataset provided, but when I tried switching to my own coordinates, I encountered issues and did not see any results. Does anyone have ...

Having trouble making this button function in HTML/JavaScript?

As a beginner learning Javascript by following a tutorial, I tried to copy this code exactly as shown but it's not functioning as expected. The video tutorial was created in 2015 so I'm wondering if there have been any changes to the language sin ...

From HTML to Python to Serial with WebIOPi

I am facing a dilemma and seeking help. Thank you in advance for any guidance! My project involves mounting a raspberry pi 2 b+ on an RC Crawler rover, utilizing WebIOPi for the task. However, I am encountering challenges and unable to find useful resourc ...

Guidelines for setting the Id and value for a Hidden field

I am working with a gridview that has a few rows and columns, each containing ListBox Controls. Markup: <asp:GridView ID="gvDataEntry" runat="server" AutoGenerateColumns="False" <Columns> <ItemTemplate> <asp:ListBox ID="lst ...

A guide on storing data in a database with AngularJS within the Django framework

My project utilizes the Django framework along with AngularJS. I am looking to save all the values entered in my HTML page to the Database upon clicking submit. I have heard that a simple submit button is needed and most changes will be made in views.py. S ...

Exploring the method of displaying a JSON 2D array through the utilization of getJSON

Is there a way to read 2D JSON data? An example of a JSON file is given below: [ { "name":"Menu1", "permission":"1", "link":"http://naver.com" }, { "name":"Menu2", "permission":"2", "link":"http://daum.net", ...

JavaScript does not always display the correct results for past day dates

I am trying to retrieve a date in the "YYYY-mm-dd" format from some days ago using the following function: function getDifDate(d, numd) { d = stringToDate(d); d.setDate(d.getDate() - numd); return d; } Subsequently in another section of the program, I ...

Angular - Utilizing Mat Paginator with Multiple Tables within a Single Component

I've been struggling with an issue for quite some time now, trying to find a solution but nothing seems to be working. Currently, I am facing an obstacle while rendering five tables on the screen. The data for these tables is fetched using a GET call ...