h404 h404 - 24 days ago 13
Javascript Question

Very slow loop in angularjs

I use this loop for create map markers (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;


how I can improve the for loop speed in angularjs (currently it takes almost 10s)?

Answer

There is a few things that can improve your code speed like avoiding eval and caching loop variables and arrays as well. By caching some values, reduce a bunch of operations like member access and unecessary calculations.

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;

Comments