Using jQuery or JavaScript can become sluggish when processing more than 2000 rows

I currently have a total of 2000 rows in my dataset, with each row structured as shown below:

<div class="rr cf">
    <span>VLKN DR EXP</span>
    <span>01046</span>
    <span>VELANKANNI</span>
    <span>20:30</span>
    <span>DADAR</span>
    <span>10:00</span>
</div>

When a button is clicked, I am scanning for text within each row and then adjusting the display property to either block or none. The code responsible for this operation is as follows:

$('.rr').each(function(){
    this.style.display="block";
});

var nodes = $(".rr");
for(var i=0;i < nodes.length; i++) {
     // if data found
         nodes.get(i).style.display="block";
     // else
         nodes.get(i).style.display="none";
}

This method seems to be quite sluggish, as it triggers a Chrome alert prompting to kill the page.

Do you have any suggestions on optimizing this process? Any ideas on how we can enhance the performance here?

Answer №1

Improving Loop Performance with Local Variables


One effective strategy to enhance the efficiency of a loop is to decrement the iterator towards 0 instead of incrementing towards the total length. Implementing this simple adjustment can lead to significant savings, potentially reducing the original execution time by up to 50%, depending on the complexity of each iteration.

Source:

  • To optimize performance, consider storing the value of nodes.length as a local variable to avoid recalculating it in each iteration.
  • You can also increase efficiency by assigning nodes.get(i) to a local variable if you frequently access that data.
  • If the order of operations is irrelevant, contemplate decrementing the for loop towards 0 rather than counting upwards.
  • It's worth noting that jQuery's each() loop tends to be slightly slower compared to manual iteration. For a comparison, refer to this link.

For a straightforward illustration, check out this example:

In the example provided, I have condensed the loop using a while loop:

var nodes = $(".rr span");
var i = nodes.length;

while(i--){ 
  if(i%2 === 0){
    nodes.get(i).style.color = "blue";}
}​

Observe how the while loop decreases i with each iteration. Hence, when i = 0, the loop terminates because while(0) evaluates to false.


Optimizing Array Processing through Chunking


The chunk() function is designed to segment an array into smaller parts for efficient processing. It takes three parameters: a list of items to process, the processing function for each item, and an optional context variable to define the value of 'this' within the processing function. By introducing timers between processing stages (e.g., every 100ms), the function removes and processes one item at a time until all items are dealt with.

If you require a method to execute loops in sections to prevent browser crashes, explore Nick Zakas's chunk method outlined here.

function chunk(array, process, context){
    setTimeout(function(){
        var item = array.shift();
        process.call(context, item);

        if (array.length > 0){
            setTimeout(arguments.callee, 100);
        }
    }, 100);
} 

Enhancing Performance with createDocumentFragment()


By utilizing the document fragment concept, changes made off the main DOM tree do not trigger page reflow, leading to improved performance outcomes. Document fragments are universally supported across browsers, including Internet Explorer 6, making them a versatile tool for enhancing web application speed.

Reflow refers to the computation of layout engine formatting objects' geometry during rendering.

Since iterative display property adjustments prompt window repaints, consider using createDocumentFragment to minimize repainting requirements. By consolidating all modifications within the fragment before updating the DOM, you reduce unnecessary repaint cycles.

Answer №2

Initially, it's important to identify the root of the delays - are they happening within the jquery script or during the data validation process? If the issue lies within the jquery code, one potential solution is to temporarily remove the data container element (the HTML element that houses all the .rr divs) from the Document Object Model (DOM), make necessary modifications, and then reintegrate it. By taking this approach, you can prevent the browser from repeatedly re-rendering the DOM after each alteration.

Answer №3

Here's a suggestion:

1) Hide the common parent element by setting its display property to "none"

2) Iterate through each individual div, adjusting their display property as needed

3) Finally, restore the parent element's display property to "block"

This approach allows the browser to optimize rendering updates by consolidating changes rather than processing them individually. When the parent element is hidden, there's no necessity for the browser to render updates for each child node until the parent becomes visible again.

Additionally, it seems redundant to initially loop through all the child nodes and set them to block before looping through them again to set their actual intended values.

Answer №4

Avoid using jQuery in this situation, as it may cause unnecessary delays.

    var items = document.getElementsByClassName('rr'),
        count = items.length;

    for(var j = 0; j < count; j++)
    {
        var item = items[j];
        if(item.innerHTML.search(/01046/) != -1)
            item.style.display = "none";
    }

This approach should yield better performance results.

Answer №5

When dealing with a large set of roughly 1500 items, I encountered performance issues during the looping process.

The bottleneck was not the loop itself, but rather the operation being performed within it.

To address this issue, I implemented a solution using setTimeout to stagger the load and maintain browser responsiveness during updates.

var _timeout_ = 0;
for(var i=0;i < nodes.length; i++)
{
    setTimeout(
        (function(i)
        {
            return function()
            {
                if(stuff)
                {
                    nodes.get(i).style.display="block";
                }
                else
                {
                    nodes.get(i).style.display="none";
                }
            }
        })(i),
        _timeout_
    );
    _timeout_ += 4;
}

This approach introduces a delay of 4 milliseconds between each update. Adjusting the timing based on the operation duration can help prevent browser unresponsiveness. Experiment with different timings, such as setting it to 3 if the slowest browser takes only 2 milliseconds for the operation.

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

Best practices for storing and utilizing data collected from an Angular Form

This is the code I have been working on: Here is my component.html: <div class="container"> <Form #a ="ngForm" ngForm (ngSubmit)="onSubmit(a)"> <div *ngFor="let question of questions"> ...

What sets apart getNamedItem() from getAttribute()?

Do both provide attributes of an XML element? Is there any distinction between the two? ...

The DELETE method is not permitted in Angular JS 405

I'm encountering an issue with my Angular code: DepartmentController.prototype.delete = function (id) { this.departmentResource.delete(id); }; The error message I'm receiving is: DELETE http://localhost:64956//api/departments 405 (Method N ...

Creating Dynamic Types in TypeScript Based on React State

As part of my project, I am developing a versatile useFetch hook that will be responsible for handling data fetching operations. The hook should return an object with different properties based on whether the fetch operation was successful or encountered a ...

Properly configuring the root directory to troubleshoot Axios 404 POST issues within a Vue Component coupled with Laravel

As I delve into learning Vue+Laravel through a tutorial, I have encountered an issue with Axios when making an Ajax request within the script of a Vue Component. The console log error that is troubling me reads as follows: POST http://localhost/favori ...

Step by step guide on transferring textbox value to hidden field

Within my GridView, there is a button at the bottom that allows users to add notes. Upon clicking this button, a pop-up window appears for users to input their note. It is essential for the system to retain the text of the note so that when the pop-up clos ...

transferring various data from JavaScript page to PHP page

Is it possible to pass multiple values from a service page to a PHP page? I am trying to pass the values 'data', 'albimg' and 'albvideo' to the PHP page, but I keep encountering an error. Please refer to the image below for mo ...

Creating a script to open multiple URLs in HTML and JavaScript

Currently, I am working on creating a multiple URL opener using HTML and JavaScript. However, I have encountered an issue where HTTP links are opening fine but HTTPS links are not. Can someone provide assistance with this problem? Below is the code snippet ...

Simulating require statements using Jest

Addition.js module.exports = function add(a, b){ return a + b; }; CustomThing.js var addition = require("./addition"); module.exports = class CustomThing { performAddition(a, b){ return addition(a, b); } } CustomThingTest.js test( ...

Loop through a JSON object to dynamically update the value of a specific key

I have a JSON object with keys and values, where some of the values are empty strings. I want to replace those empty values with the corresponding key name. However, when trying to get the value of a key within the loop, it returns undefined. JSON: "Forg ...

Error encountered: ReferenceError when using node.js, express, ejs, bcrypt,

Recently started diving into node.js and encountered an issue when trying to merge code from various projects. Everything was functioning smoothly until I switched the route path from '/dashboard' to '/store' along with the correspondin ...

What is the best way to send props to a component that is exported using a Store Provider?

I'm trying to export my react component along with the redux store Provider. In order to achieve this, I've wrapped the component with an exportWithState callback. However, I'm facing an issue where I can't seem to access the props that ...

Updating an item stored locally

I am currently working on a web application that utilizes local storage. I have successfully implemented functionality to add and delete items, but I am facing an issue with editing items. Although items can be edited as expected, upon refreshing the page, ...

Having difficulty handling redirections in Node.js

I am encountering a new issue with the code provided. My goal is to create a simple login system, but I am facing difficulties in redirecting users using res.redirect('/example'). When attempting to redirect users, the console.log indicates that ...

Combining all CSS files into one and consolidating all JavaScript files into a single unified file

Whenever I need to add a new CSS or JS file, I always place it in the header section like this Add CSS files <link rel="stylesheet" href="<?php echo URL; ?>public/css/header.css" /> <link rel="stylesheet" href="<?php echo URL; ?> ...

Verify whether the element within an iFrame contains any content

After conducting extensive research, I have been unable to find a satisfactory answer to my question. Therefore, I am reaching out to see if anyone has the knowledge I seek. The Goal: I aim to check the contents within an iFrame and determine whether it ...

JavaScript transforming an array into a counter

I am seeking a way to transform a one-dimensional array into a frequency dictionary in JavaScript. The array elements should serve as keys, while their frequencies act as values. Take, for example, the Python script below, which generate a list of 1024 ra ...

The login process in Next-auth is currently halted on the /api/auth/providers endpoint when attempting to log in with the

My Next-auth logIn() function appears to be stuck endlessly on /api/auth/providers, as shown in this image. It seems that the async authorize(credentials) part is not being executed at all, as none of the console.log statements are working. /pages/api/au ...

Flexbox element in React not resizing to fit width

I've been working on a slide carousel and it's almost complete, but I'm facing an issue with adjusting the arrows to the images. When testing the website for responsiveness, I noticed that the div inside the flexbox stops shrinking and rema ...

Show some text when the ReactJS icon is hovered over

As a beginner with React, I am trying to show text when the user hovers over an icon. Currently, I am using material-ui along with the latest version of Reactjs. Below is the code snippet that I last tried: return ( <List className={classes.list ...