AngularJS experiencing sluggish performance

Below is the loop I am using to create map markers with 1000 points:


        var markers = {};
        for (var i = 0; i < items.data.data.length; i++) {
            latVal = items.data.data[i].lat;
            lngVal = items.data.data[i].lng;
            ikona = icons.infost;
            message = "<b>" + items.data.data[i].name + "</b>";
            markers[i] = {'group': 'cmp', 'lat' : eval(latVal), 'lng' : eval(lngVal), 'icon' : ikona, 'message' : message};
        }
        $scope.Markers = markers;
    

Any suggestions on how to enhance the speed of this for loop in AngularJS? Currently, it takes almost 10 seconds.

Answer №1

  1. Avoid using eval. It can slow down performance and negate browser optimizations throughout the function chain.
  2. Opt for an array like markers = [] over an object.
  3. Utilize the + operator to convert strings to numbers efficiently.
  4. Use push method when adding elements to arrays.
  5. Store results from items.data.data in a variable for better organization.

Answer №2

Improving the speed of your code involves avoiding using eval and caching loop variables and arrays. By caching certain values, unnecessary calculations and member access operations can be reduced.

var items = { data: { data: [] }};
var icons = { infost: 'infost'};
for (var i = 0; i < 1000; i++) {
  items.data.data.push({ lat: ''+i, lng: ''+i, name:''+i });
}

console.time('time');

/// YOUR CODE STARTS HERE

var
  data = items.data.data,
  l = data.length,
  markers = Array(l), // or just []
  item, latVal, lngVal, ikona, message;

for (var i = 0; i < l; i++) {
  item = data[i];

  latVal = item.lat;
  lngVal = item.lng;
  ikona = icons.infost;
  message = "<b>" + item.name + "</b>";
  markers[i] = {
    group: 'cmp',
    lat: +latVal,
    lng: +lngVal,
    icon: ikona,
    message: message
  };
}
console.timeEnd('time');
//$scope.Markers = markers;

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

Top Tip for Preventing Angular Version Compatibility Issues

Here is an illustration that delves into my inquiry ----> Version Conflict The dilemma arises when my product has a dependency on a node package, which in turn relies on a specific version of Angular, denoted as version #y. However, my product itself ...

Is it possible to pass arguments to setTimeout function?

At the current moment, my code looks like this: function showGrowl(lastNumber) { var num = lastNumber; //keep generating a random number untill it is not the same as the lastNumber used while((num = Math.ceil(Math.random() * 3)) == lastNumber); ...

Fade in and out of div elements upon clicking on an # anchor

I have been attempting to create a function where different divs fade in and out when clicking on an image with an <a href>. Unfortunately, I have not been successful in getting it to work despite several attempts. Here is the code that I am using: ...

Unable to transmit props through components with Vue router

Hey there, I'm currently facing an issue with passing props from my vue router. It seems like nothing is being printed and when I checked in the mounted hook, it's returning undefined. However, strangely enough, when I use console.log(this.$route ...

Trigger an immediate Primefaces update using a JavaScript function

Having an issue where: upon page load, I attach a 'keypress' event listener to every input field on the page. The goal is to check for special characters in the input and remove them. Below is the function that executes on page load: function ...

Removing borders from textField in ReactJS can be achieved using a combination of CSS

Is there a way to remove the border from a TextField component? <Box display="flex" alignItems="center" border="1px solid #ccc" borderRadius="4px" paddingLeft="10px"> <Typography variant=&quo ...

Updating the color with the help of useState in React, with the use of Material

I enjoy changing the color of the icon with a click using a useState hook. I have added a click handler to the icon for this purpose. Below is the code snippet: import React, { useState } from 'react'; import './App.css'; import ThumbU ...

Pass data dynamically to router in ExpressJS

Within my app.js file, there are several variables defined: var user = "max"; Additionally, there is a route function set up like so: app.post('/register', user.postRegister); In the /routes/user.js file, there is a module function structured ...

Adding a jPlayer on the fly

I've been working on a code snippet to dynamically add jPlayers through a function. Here is the code I have so far: function audio_player(audio, title, type) { var id = $('.audio').length; $('#audio').append('<di ...

Encountering an issue... invariant.js:42 Error: A `string` value was received instead of a function for the `onClick` listener

Currently, I am working on creating a form that allows users to build quizzes without any restrictions on the number of questions they must include. To achieve this, I plan to add an "add question" button at the bottom of the quiz form, allowing users to d ...

What is the best way to extract hover-box information from an ajax website with Python?

Attempting to extract the dimensions for each cell on a map from this AJAX site, where details only appear when hovering over the cells has proven unsuccessful so far. Using Python selenium webdriver and phantomJS did not yield any data when trying to loa ...

Check to see if the property of the object does not exist within the array and update as

My goal is to add the variable content into the database content using the $push method, but only if the content.hash doesn't already exist in the database. I want to avoid duplicating information unnecessarily. return shops.updateAsync({ "user": u ...

Converting HTML and CSS into a PDF using JavaScript

I am on the lookout for libraries that can cater to my specific needs, as I haven't found one that fits perfectly yet. My setup involves Node.js on Express.js for the backend, and html/css/js for the front-end. Browser support includes IE8 and up, chr ...

Unlocking the potential: Clicking on all ng-if elements with matching text using Chrome console

I am currently trying to determine how to automatically click on all elements that have a specific state. The page appears to be built using Angular, although I am unsure of the exact version being used. My approach involves using the console in Chrome t ...

Display markers on the canvas

I am having trouble painting points from a JSON object on canvas using the following code. Can someone help me identify where I went wrong? var c = document.getElementById("myCanvas"); var ctx = c.getContext("2d"); var t = [{"prevX":39,"prevY":58,"currX ...

How can I remove the script from Response.Write?

Instead of using Response.Write to test some values in code with an alert box, I tried writing dynamic javascript directly into the page. Even after reverting the code, rebuilding, and clearing all temp data from IE, the alert still pops up. I followed a ...

Creating a Vue.js component during the rendering process of a Laravel Blade partial view

In my Vue.js project, I have a component that is used in a partial view called question.blade.php: {{--HTML code--}} <my-component type='question'> <div class="question">[Very long text content...]</div> </my-component& ...

How do you properly end a mongoDB connection?

Here is a snippet of the code I've been working on. In the findCollection function, I am retrieving a database service and returning the collection. This function is used in other places like the Base class, which is then utilized elsewhere. My main c ...

Tips for managing the DeviceNotRegistered issue with the expo-server-sdk-node package

For my backend, I created a push notification system using expo-server-sdk-node. When it comes time to send notifications, I retrieve the expoPushToken from my database. The documentation mentions that the following error(s) should be addressed: DeviceNo ...

Upon refreshing the page, the React application alters the font style

While working on my ReactJS application, I noticed that the font changes after the page loads and then reloads. Take a look at the examples below: Before reloading (press f5): https://i.sstatic.net/tJFjU.png After reloading (press f5): https://i.sstati ...