The loop within a loop is causing excessive lag and is on the verge of crashing the

I need help with optimizing the performance of my app that retrieves json data. The json file contains nearly one thousand words structured like this:

{"THEMES":{"THEME1":["ITEM1","ITEM2","ITEM3"],"THEME2":["ITEM1",...]...}}

The size of the file is around 25kb. In a specific part of my application, I have to match each ITEM with its corresponding THEME in order to display a selected item related to a word using angular ng-repeat. Below is the section of my angular code that handles this functionality:

<div class="well">
    <div class="input-group" bindonce ng-repeat="word_in_list in words_list">
        <div class="form-group">
            <select>
                <option ng-selected="word_in_list.select == theme" ng-repeat="theme in themes" value="{{theme}}">{{theme}}</option>
            </select>
        </div>
        <div class="form-group">
            <input type="text" class="form-control" placeholder="{{word_in_list.input}}">
              <span class="input-group-addon">
                <input type="checkbox" ng-click="listControlWord($event, word_in_list.input, word_in_list.select)">
              </span>
        </div>
    </div>
</div>

The crucial part lies here:

$http.get('json/word_bank.json')
    .success(function (result) {
        $scope.themes = Object.keys(result.THEMES);
        for (var i = 0, z = $scope.themes.length; i < z; i++) {
            for (var j = 0; j < result.THEMES[$scope.themes[i]].length; j++) {
                $scope.words_list.push({select: $scope.themes[i], input: result.THEMES[$scope.themes[i]][j]});
            }
        }
    });

The problem is that browser rendering takes too long, sometimes crashing the browser due to the excessive time taken. Despite the loops functioning correctly and data retrieval being successful, the slow rendering speed is not acceptable. What can I do to optimize these loops?

Answer №1

Your algorithm seems to have a time complexity of O(N^2), and unless you incorporate domain-specific heuristics, there may not be a way to improve it significantly. However, looking at the problem from a different angle, it appears that you are essentially concatenating arrays.

For a performance test related to your task, you can refer to the provided link.

Although leveraging apply for maximum efficiency might not be feasible in this case, you could combine various techniques. By concatenating all arrays and maintaining metadata about how indexes in the concatenated array correspond to specific "keys," you might reduce the complexity to O(N).

One possible solution could be...

<!doctype html>
<html lang="en">
    <head>
        <title>Test</title>
        <script src="d3.js" charset="utf-8"></script>
    </head>

    <body>
        <div id="divPerfTest"></div>

        <script>
            var result = {"THEMES":{"THEME1": ["ITEM1","ITEM2","ITEM3"],"THEME2":["ITEM1","ITEM2"]}};
            var keys = Object.keys(result.THEMES),
                master = [],
                masterBreaks = [],
                themeNames = [],
                word_list = [],
                theme, idx, key,
                breakIdx = 0,
                breakOffset = 0,
                outStr = "";


            for(idx = 0; idx < keys.length; idx++) {
                key = keys[idx];
                theme = result.THEMES[key];
                master = master.concat(theme);
                masterBreaks.push(theme.length);
                themeNames.push(key);
            }

            masterBreaks.push(master.length); // need the last break to exceed last index

            for (idx = 0; idx < master.length; idx++) {
                if (idx >= masterBreaks[breakIdx] + breakOffset) {
                    breakOffset += masterBreaks[breakIdx++];
                }

                word_list.push({
                    select: themeNames[breakIdx],
                    input: master[idx]
                });
            }

            for(idx=0; idx<word_list.length; idx++) {
                outStr += "[ " + idx.toString() + " ] Select: " + word_list[idx].select + ", Input: " + word_list[idx].input + "<br/>";
            }

            document.querySelector("#divPerfTest").innerHTML = outStr;
        </script>
</body>
</html>

Alternatively, consider revisiting your data schema. Instead of using variable names to represent different themes, is there a way to reorganize or manipulate the data so that each object includes a theme name attribute along with its corresponding list of items? This way, you maintain a list of these objects...

{ THEMES: [
    { id: "THEME1",
      data: ["ITEM1", "ITEM2"] },
    { id: "THEME2",
      data: ["ITEM1", "ITEM2", "ITEM3"] }
}

Answer №2

To enhance efficiency while looping through an array, consider dividing the task into segments and implementing timers to handle each segment separately in iterations rather than all at once.

For more information on how JavaScript timers function, you can visit:

Answer №3

After some perseverance, I was able to resolve the pagination problem in my application. The solution I found was from this source: Improving AngularJs Performance for Large Lists

I hope that sharing this helps someone else facing a similar issue. Best regards.

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

Tips for transferring information from one php page to another php page via ajax

I am attempting to retrieve data from one PHP page and transfer it to another page through the use of Ajax. JavaScript : $.ajax({ url: "action.php", success: function(data){ $.ajax({ url: "data.php?id=data" ...

The Three.js duplication tool replicates all mesh data from the original volume and its associated child nodes

In my quest to generate a 3D model of intricate geometry (specifically nuclear physics particle detectors) using ThreeJS, I encountered a challenging situation. One particular example involves handling around 100,000 geometries and a staggering 4.5 million ...

The functionality of the anchor tag is restricted in both Chrome and Safari browsers

I'm having an issue with HTML anchor tags not working properly in Chrome and Safari. Instead of scrolling up, the page scrolls down when clicked. Here is the HTML code I'm using: <a id="to-top"></a> <a class="button toTop" href="# ...

Using jquery to toggle active nav links in Bootstrap

I'm currently working on integrating a jQuery function to automatically update the active status of the navigation links in my Bootstrap Navbar. The structure involves a base HTML file that extends into an app-specific base file, which is further exte ...

Extract keys enclosed in quotation marks using regular expressions

My coding challenge involves working with JSON data in a specific format: define({ somekey : "Some {text} here:", 'some-key' : "Text:", 'key/key' : 'Some : text', key: 'some value', 'my-key' : &a ...

Understanding the relationship between csv and json array formats, along with the process of converting them into a json array using Node.js

Greetings! I have been searching for quite some time and have not been able to find the desired result. I am unsure of what a CSV file would look like with the following JSON array: [ { email: "<a href="/cdn-cgi/l/email-protection" class="__cf_email_ ...

Error encountered with nested v-for in Vue.JS causing null and undefined values to be thrown

Question Conclusion: A Vue component I am working on has the following data setup: conversations: null, currentConversation: null, There is a method that runs on mounted() to retrieve the user's conversations: /** * Method to retrieve the user&ap ...

Invoking a Vue method within a Laravel blade template

In my Laravel project, I have a blade that is loading a Vue component successfully. However, I am facing an issue where calling a method in the Vue component from a select box in the blade is not working as expected. Despite having a method call set up to ...

Combining data from various lists to populate a dictionary and generate a JSON file

I am currently working with a .dat file that I need to convert to json format. The challenge is that the data in the first half of the file has an awkward format that I must handle myself, so I cannot rely on pre-existing source code. After restructuring ...

Angular Select doesn't seem to be updating when the model changes

I have been working on a website that utilizes Angular (version 1.6.4) Select feature. The select element's content is fetched via a REST call the first time it is requested, and subsequently cached for faster loading from memory in subsequent calls. ...

Ways to output a string array from a JSON object containing additional attributes

On the client side, I have received a JSON object from a REST service. This object contains multiple attributes, one of which is a String array. I need guidance on how to display this array using embedded AngularJS code in HTML. Here is my JSON object: [ ...

Extracting data from JSON response

The JSON output is as follows: [{"Post":{"name":"Name1","text":"Text1"}}, {"Post":{"name":"Name2","text":"Text2"}}] In attempting to retrieve the values, I used the following code: var data = $.parseJSON(result) // converting JSON to object I tried acc ...

Troubleshooting the issue of data retrieval failure in asp.net mvc controller using jquery.post()

I am currently working on an ASP.NET MVC web application that is written in VB.NET. My goal is to send data using jQuery to my controller. Below is the code for my controller: <HttpPost()> Function GetData(p As DataManager) As JsonResult ...

Is it feasible to package shared modules into individual files using Browserify?

In my web app, I am using Browserify, Babel, and Gulp to bundle my scripts into a single file. However, when I checked the file size, it was over 3MB which seems excessive to me. Although I'm not entirely sure how Babel and Browserify modify my sourc ...

Place the image on the canvas and adjust its shape to a circle

Here is the code I used to insert an image into a canvas: <script src="https://rawgit.com/kangax/fabric.js/master/dist/fabric.min.js"></script> <button onclick="addTexttitle()" type="button" class="text-left btn-block btn white">Set Imag ...

Attaching a click event to an input field

Seeking to serve html files from the server without relying on template engines. Below is the script used to start the server. // script.js const express = require("express"); const bodyParser = require("body-parser"); const app = express(); app.use(expr ...

Tips for choosing or unselecting a row within a Table utilizing the Data Grid Mui

Is it possible to implement row selection and deselection in Mui without using the checkboxSelection prop? I am looking for a way to achieve this functionality in @mui/x-data-grid when clicking on a row. Below is the code snippet from the Table Component ...

Please send the report in a designated JSON format

views.py This snippet of the views.py file retrieves phone information and converts it into JSON format before sending it back as a response. It loops through PhoneInfo objects associated with a specific user ID and constructs a dictionary for each phone ...

Ditch the if-else ladder approach and instead, opt for implementing a strategic design

I am currently working on implementing a strategic design pattern. Here is a simple if-else ladder that I have: if(dataKeyinresponse === 'year') { bsd = new Date(moment(new Date(item['key'])).startOf('year&apos ...

Issue with JSONP success function not being triggered

Here is an example of an Ajax call being made to a different domain: <script> $.ajax({ url: 'url?callback=?', dataType: 'jsonp', success: function (data) { alert(data[0].DeviceName) ...