LeoAref LeoAref - 1 month ago 4
Javascript Question

Faster loop in Jquery

I want to update all object child values with the same value, let's do it by code:

var days = [
{
title: 'Day 1',
checked: false
},
{
title: 'Day 2',
checked: true
},
{
title: 'Day 3',
checked: false
}
];


Now if I want to updates the property
checked
for all days array nodes, I do this:

$.each(days, function(i, day) {
day[i].checked = true;
});


So, I'm looking for a better way for doing this, something like this:

days[*].checked = true;


Thanks in advance.

Answer

As I've already mentioned comment below the Question! $.each( ... ) is very costly for the performance. Though it can be only detected at large amount of data in an Array!

And as per This Article : And this Question...

Most light-weight and easy to use way is While loop:

var len = arr.length;
while (len--) {
  arr[len] *= 2;
}

Then another preferable and more treditional is do-while loop:

var len = arr.length;
do {
  arr[len] *= 2;
} while (len--);

Least preferable is Array map :

arr.map(function(el) {
  return el * 2;
});

enter image description here

And there are many other ways to loop through array and are costly than above couple of methods.

After Edit:

Disadvantages of $.each() loop :

  1. Lower performance compare to other loops (for games/animations/large datasets)
  2. Less control over iterator (skip items, splice items from list, etc).
  3. Dependency on jQuery library unlike for, while etc loops!
  4. Not familiar syntax, as most other similar languages.