Differences between using Array.from and a for loop to iterate through an array-like object

When traversing an array-like object, which method is more efficient for performance: using Array.from( ).forEach() or a traditional for loop?

An example of an array-like object would be:

let elements = document.querySelector('#someid').children;

Here is an example of iteration using Array.from().forEach():

Array.from(elements).forEach(element => {
  // do something with the element
})

Alternatively, here is an example of iteration using for:

for (let i = 0; i < elements.length; i++) {
  // do something with elements[i]
}

Answer №1

It's important to note that there are a couple of other interesting options as well:

  1. You can use the Array.from function with a second argument, which is a callback that is called for each element. This method is expected to be faster than using the .forEach method, as it eliminates the need to create an intermediate array.

  2. Another option is the ES6 for..of loop.

However, it is widely acknowledged that the traditional for loop surpasses all other alternatives. Here is a simple code snippet to measure their performance:

const childNodes = document.querySelector('#someid').childNodes;
let i, start, duration, times = 500000;

k = times;
start = performance.now();
while (k>0) {
    Array.from(childNodes).forEach(node => 
        k -= node ? 1 : 0
    );
}
duration = performance.now() - start;
console.log('Array.from with forEach: ', duration.toFixed(2));

k = times;
start = performance.now();
while (k>0) {
    Array.from(childNodes, node => 
        k -= node ? 1 : 0
    );
}
duration = performance.now() - start;
console.log('Array.from callback: ', duration.toFixed(2));

k = times;
start = performance.now();
while (k>0) {
    for (let i = 0; i < childNodes.length; i++) {
        k -= childNodes[i] ? 1 : 0;
    }
}
duration = performance.now() - start;
console.log('Oldfashioned for-loop: ', duration.toFixed(2));
    
k = times;
start = performance.now();
while (k>0) {
    for (const node of childNodes) {
        k -= node ? 1 : 0;
    }
}
duration = performance.now() - start;
console.log('for-of loop: ', duration.toFixed(2));
<ul id="someid">
    <li>test1</li>
    <li>test2</li>
    <li>test3</li>
    <li>test4</li>
    <li>test5</li>
</ul>

Answer №3

After analyzing performance on a jsperf test, it was determined that a for loop outperforms a forEach loop, while a for...in loop is the slowest option.

It should be noted that the use of Array.from is inconsequential as it is only executed once.

Additionally, in practical scenarios, the bottleneck is often attributed to operations like document.querySelector. Research on jsperf suggests that using getElementById yields better performance.

The key lesson here is to prioritize understanding use cases and maintainability over immediate performance concerns; when performance becomes a focus, it should be approached from a comprehensive perspective.

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

Chaining promises: The benefits of attaching an error handler during Promise creation versus appending it to a variable containing a promise

function generatePromise() { return new Promise((resolve, reject) => { setTimeout(reject, 2000, new Error('fail')); }); } const promise1 = generatePromise(); promise1.catch(() => { // Do nothing }); promise1 .then( ...

Customizing multi select in MUIv5 AutoComplete feature

My current challenge involves using the mui Autocomplete multi-select component. I'm having trouble getting it to function according to my specific requirements. Essentially, I need to set default selected values passed as props from the Parent compon ...

Downloading files from a Blob in NodeJS: A step-by-step guide

How do I retrieve a file from a BLOB column using NodeJS? Currently, I am utilizing the oracledb library for database operations and my code snippet is as follows: async function getFile(req, res) { let filename = req.params.filename; let file = a ...

Issues have been identified with the functionality of the Am charts v3 XY in conjunction with a

I'm currently working on a project with angularJS and utilizing the npm package amcharts3 "^3.21.15". I've encountered a minor issue regarding the logarithmic scale in my XY chart. Below is my chart without the logarithmic scale: View working ch ...

Submit a form utilizing jQuery's ajax function

I am currently facing an issue with my use of the $.ajax post method. My intention is to submit form data on the current page itself, but somehow the script is redirecting to the action page. If anyone could pinpoint what's causing this redirection ...

CSS - starting fresh with animations

I am facing an issue with a CSS animation that I created. Everything seems to be working correctly, but I need to complete it by setting the input type to reset the animation. Below is the CSS code snippet that should reset the animation: $('button& ...

Is it possible that the passing of Form Serialize and list to the controller is not functioning properly?

i am struggling with the following code in my controller: public ActionResult SaveWorkOrder(DTO_WorkOrder objWork, List<DTO_PartsWO> listTry) { //something } here is my model : public class DTO_WorkOrder { public string Id { get; set; ...

Creating a POST request in Rails 3

Is there a way to integrate web services in Rails 3 by sending POST parameters to an external URL? Typically, I utilize a command line method like the one below for posting: curl -X POST -u "v10REVkw:XuCqIhyCw" \ -H "Content-Type: application/json" & ...

The current environment does not recognize the term 'ScriptManager'

After attempting to solve a JavaScript issue following an AJAX postback in ASP.Net by implementing some code, I encountered an unexpected error during the build process: An unexpected error occurred: The name 'ScriptManager' does not exist in th ...

Navigate through a JSON data structure containing nested arrays

Does anyone know an effective way to loop through a JSON object that contains two or more nested arrays? The goal is to extract the values from each array without including key-value pairs in the output. {"Obj": ["array 0", ["nested array 1"], ...

Is there a way for me to control the permissions granted to jhipster's authorities?

In the process of developing a web application with JHipster code generator, I have extended the pre-existing roles to a total of 5: ROLE_USER, ROLE_ADMIN, ROLE_ANONYMOUS, ROLE_PRESIDENT, ROLE_VICE_PRESIDENT I am now seeking guidance on how to manage per ...

Can you explain the meaning of the code provided below?

I'm having trouble understanding the functionality of this code snippet: .bind(this); (I copied it from the Zurb Foundation dropdown plugin) .on('mouseleave.fndtn.dropdown', '[data-dropdown], [data-dropdown-content]', function ( ...

Angular Unit testing error: Unable to find a matching route for URL segment 'home/advisor'

Currently, I am working on unit testing within my Angular 4.0.0 application. In one of the methods in my component, I am manually routing using the following code: method(){ .... this.navigateTo('/home/advisor'); .... } The navigateTo funct ...

Is it possible to exponentiate an array by another array's power?

If I have a data structure named VeryBig which consists of a size and an array of int type capable of holding large numbers. Given two arrays, base->arr with elements 9,8,7,6,5,4,3,2,1 and exponent->arr with elements 1,2,3,4,5,6 struct VeryBig{ ...

What is the process for extracting JSON values by specifying keys within a nested JSON structure?

I am attempting to extract specific JSON values for particular keys from a JSON structure. I have made the following attempt: var jsonstring; jsonstring = JSON.stringify(myjsonObjectArray); alert(jsonstring);//displaying the JSON structure below jsonstri ...

Comparison of Angular.js formsets to Django's formset

Within Django, formsets allow for the use of multiple forms within one larger form. For example, you can add multiple books to a library formset by repeating the same book form with details such as author and title. I am looking to achieve similar functio ...

JQuery Datatables: Struggling to make JQuery function work following AJAX update

Watch this screencast to get a clearer understanding of the issue.... I'm currently working on my first project involving AJAX, and I'm encountering some obstacles. The datatable is loading user details from a JSON output using AJAX. Each row ...

Divide the linear dataset and compute the maximum value using PHP

When analyzing my data, I have a series of results that look like this: 0.0450.0230.0560.0620.0420.0100.0730.0470.0780.0570.0040.0550.0500.0500.039 My goal is to calculate the maximum value in this dataset. Here is the code I have tried: //example $data = ...

Error: unable to locate the react-redux context value; make sure the component is enclosed in a < Provider > tag

import React, { Component } from 'react' import { createStore } from 'redux' import { Provider, connect, useSelector } from 'react-redux' function rootReducer(state = { name: 'store' }, action) { return state ...

User retrieval failed following successful passport authentication

After a successful authentication, the user is directed to the "/profile" route, as demonstrated in the code snippet below. app.get( "/auth/google/callback", passport.authenticate("google", { successRedirect: "/profile", failureRedirect: " ...