Choosing Between PureFor and ES6 Map: A Comparison

I prefer writing Pure For(nested Fors) in JavaScript instead of using map because I have found it to be more efficient in terms of performance. Is this True or am I making a mistake repeatedly?

If For is quicker, but Map is cleaner, which one should I choose?

As I am not proficient in ES6 Map, could someone provide a cleaner way to write the code below using map?

let categoriesDataArray = [];
let productsDataArray = [];
if (!this.props.categoriesIsFetching) {
    for (let i = 0; i < this.props.categories.length; i += 1) {
        for (let j = 0; j < this.props.products.length; j += 1) {
            if (
                this.props.categories[i]._id === this.props.products[j].category_id
            ) {
                productsDataArray.push(this.props.products[j]);
            }
        }
        categoriesDataArray.push({
            title: this.props.categories[i].title,
            data: productsDataArray
        });
        productsDataArray = [];
    }
}

Answer №1

It's not always the absolute best choice to prioritize performance above all else. Is shaving off 1-2 ms from a task that only runs once a minute really worth it? For me, readability and error prevention take precedence.

When For is faster and Map is cleaner, how do you determine which one is the better option?

Cleaner code is preferred until actual performance issues arise. In such cases, it's important to debug where these performance problems are coming from instead of blindly refactoring and "optimizing."


However, your code may have a larger performance issue beyond just using for versus map. The problem lies within your approach involving nested loops.

Your current implementation requires iterating through all products for each category.

let categoriesDataArray = [];

if(!this.props.categoriesIsFetching){   
    categoriesDataArray = this.props.categories.map(category => {
        return {
            title: category.title,
            data: this.props.products.filter(product => product.category_id === category._id)
        }
    });
}

Sometimes this approach works fine. It's simple and expressive, but as your arrays grow in size, the execution time will significantly increase. In such scenarios, adopting a different approach would be more beneficial than debating between for-loops or Array#map.

You can achieve the same task by iterating over each array once and utilizing a map operation, resulting in a runtime of O(n+m) rather than O(n*m).

let categoriesDataArray = [];

if(!this.props.categoriesIsFetching){
    const productsByCategoryId = {};

    categoriesDataArray = this.props.categories.map(category => {
        return {
            title: category.title,
            data: productsByCategoryId[category._id] = []
        }
    });

    this.props.products.forEach(product => {
        if(product.category_id in productsByCategoryId)
            productsByCategoryId[product.category_id].push(product);
    });
}

or as loops:

let categoriesDataArray = [];

if(!this.props.categoriesIsFetching){
    const productsByCategoryId = {};

    for(let i=0; i<this.props.categories.length; ++i){
        let category = this.props.categories[i];
        let data = [];

        productsByCategoryId[category.__id] = data;
        categoriesDataArray[i] = {
            title: category.title,
            data: data
        }
    }

    for(let j=0; j<this.products.categories.length; ++j){
        let product = this.products.categories[j];

        if(product.category_id in productsByCategoryId){
            productsByCategoryId[product.category_id].push(product);
        }
    }
}

Answer №2

ES6 map offers a cleaner solution and helps prevent undesirable scope errors and object mutations. It has completely replaced the need for using for loops and forEach once I made the switch to ES6.

Answer №3

Typically, for loops are faster in most cases.
If you want to confirm it yourself: https://jsperf.com/map-vs-for-loop-performance/3

My recommendation: Utilize all the fantastic JavaScript functionalities available and utilize a code optimizer such as Google Closure or Babel (with appropriate plugins like babel-plugin-loop-optimizer) to compile your code for enhanced performance.

Here's another illustration showcasing how choosing one looping technique over another can significantly impact efficiency: https://jsperf.com/for-vs-foreach/38
Hence, using an optimizer whenever possible is advisable.

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

Utilizing Angular 5 routerLink for linking to absolute paths with hash symbols

I am facing an issue with a URL that needs to be opened in a new tab. Unfortunately, Angular generates this URL without the # symbol. Currently, we have implemented the following: <!-- HTML --> <a title="Edit" [routerLink] = "['/object/objec ...

Transmit form information using jQuery's ajax JSON functionality

Hello, I am new to PHP/jquery and I have a question. I would like to know how to send JSON data from a form field (such as name, age, etc.) using AJAX in a JSON format. I have searched for relevant information on this but couldn't find anything concre ...

What is the process of configuring the "debuggerAddress" Chrome option using the selenium-webdriver JavaScript API?

One of the recognized "capabilities" in Webdriver is the "debuggerAddress," but I am having trouble finding a way to set this option in either the Capabilities class or ChromeOptions in the JavaScript API. It seems that setting the "debuggerAddress" option ...

Using typecasting method to extract value from a JSON object

Struggling with a JavaScript and JSON issue. There's a function that includes a JSON object: blah=function(i){ var hash= ({ "foo" : "bar", "eggs":"bacon", "sausage":"maple syrup" }); var j=eval(hash); // Convert to Object console.log(j.toSou ...

Tips on transferring information from a child component to a parent component

Currently, I am exploring ways to transfer data from a child component to a parent component. After extensive research, I have yet to find a satisfactory solution. If anyone has a solution, could you please explain how to solve this issue? APP.js impor ...

Obtaining an Array from an API GET Call

One API I'm working with has the following structure: { "author": [], "categories": [], "_id": "62ff04704bcdbd99716e0cc4", "kind": "books", "items": [ { "ti ...

Tips for adjusting the height of both an iframe and a div to fit perfectly at 100% combined

Struggling to make an iframe and div both have 100% full height on the page? I need a footer menu with 280px height, leaving the rest of the page for the iframe. After extensive research, it seems like jQuery might be necessary as CSS Flex didn't wor ...

Incorporating FaceBook into a PhoneGap Application

Currently, I am working on integrating Facebook into my phonegap/cordova application. To guide me through the process, I am using the resources provided in this link: https://github.com/davejohnson/phonegap-plugin-facebook-connect/ Even though I have bee ...

The JavaScript require() function appears to be malfunctioning

Why am I encountering an error when trying to import a valid node_module? <script > var Twit = require('twit'); </script> Error: Uncaught ReferenceError: require is not defined I am puzzled as to why the require() function wor ...

Double Looping of Ajax on Shopify Order Form

I have an Ajax order form on a product page. Every time the #submit-table button is clicked, it should display a drop-down menu with updated cart information, such as quantities and prices, along with the newly added products. Here's an example of th ...

Adjusting color schemes for Twitter Bootstrap Tooltips according to their placement

I have been attempting to customize the colors of tooltips (specifically from Twitter Bootstrap), but I am encountering some difficulties. While changing the default color was straightforward, altering the colors for .tooltip and its related definitions ha ...

Is there a way to integrate a MySQL database with parcel-bundler in a Node.js environment, or is there a simpler method to achieve this database integration with parcel-bundler?

Node.js and parcel-bundler are new to me, but I've managed to create a server.js file that connects to the database without any issues. Server.js const express = require('express'); const mysql = require('mysql'); //Establish con ...

Cycle through the list and populate the table with the data

My attempt to clarify this explanation is my best, as articulating exactly what I am trying to achieve is quite challenging: Initially, I have a list of names: { "Items": [ { "Id": 0, "Name": "Robinson" }, ...

Personalize the iOS smartbanner

We have a plan to incorporate smart banners into our app. Is there a way to personalize the smart banner so that the close button is hidden and cannot be closed by the user? I attempted to use a jQuery plugin (https://github.com/jasny/jquery.smartbanner) ...

Python dataframe iteration to validate if a value falls within the range of two adjacent columns

I have a dataset that looks like this: >data level value lev.0 1000 lev.1 1200 lev.2 1400 lev.3 1600 lev.4 1800 lev.5 2000 lev.6 2200 lev.7 2400 lev.8 2600 My goal is to identify the lowest level wher ...

The customized sweet alert button is failing to trigger its designated function

I integrated vue-swal to show a pop-up dialog with customized functionality. However, I faced an issue while modifying the swal. In my modified version, there are 3 buttons each with specific actions that should be triggered upon clicking. But for some rea ...

Prevent page flickering by implementing jQuery AJAX techniques

The code snippet above is triggering a flicker on the entire page: $(document).ready (function () { console.log("whole page disappears here"); $( "#progressbar" ).progressbar({value: 0}); queryTimer = setInterval(heavyFlicker(), 500); }) ...

Maintaining the integrity of Jquery Tab even after refreshing the page is essential

I recently started using Jquery and encountered an issue with tab implementation. Whenever I refresh the page, it automatically directs me back to the initial tab setting. $(function() { var indicator = $('#indicator'), i ...

Swapping out image sources using a React Hook that includes an onClick event

Despite my best efforts, I have yet to find a solution to this problem. To keep things brief, I am attempting to implement a dark mode toggle in my React application, but my current method feels like a hack. The main issue I am facing is changing the imag ...

What's the best way to toggle the visibility of an input-group in Bootstrap?

Is there a way to properly hide and show a Bootstrap 5 input-group? You can see an example here: https://jsfiddle.net/o08r3p9u I'm facing an issue where once the input group is hidden, it doesn't show correctly when displayed again. How can I e ...