Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Which is fastest: $.each, .ForEach, for-loop or something else? [closed]

I couldn't decide if I should go with $.each(array, function(){...}) or array.ForEach(...) or something else. So I've called the might google that gave me this link, which is fantastic if it's reliable.

According to that, there's a huge difference in speed between different approaches. Also, generally, a for-loop seems to be preferred.

I'm not a guru on JavaScript so I'd like to get some input from some JS-savvy members.

like image 528
Konrad Viltersten Avatar asked Jun 22 '13 17:06

Konrad Viltersten


People also ask

Which one is faster for loop or forEach?

Foreach performance is approximately 6 times slower than FOR / FOREACH performance. The FOR loop without length caching works 3 times slower on lists, comparing to arrays. The FOR loop with length caching works 2 times slower on lists, comparing to arrays.

Is for loop faster than other loops?

Efficiency, and While vs For Using for: % Time elapsed: 0.0010001659 seconds. Using while: % Time elapsed: 0.026000023 seconds. The main reason that While is much slower is because the while loop checks the condition after each iteration, so if you are going to write this code, just use a for loop instead.

Are for loops faster than forEach JS?

forEach is almost the same as for or for..of , only slower. There's not much performance difference between the two loops, and you can use whatever better fit's the algorithm. Unlike in AssemblyScript, micro-optimizations of the for loop don't make sense for arrays in JavaScript.


2 Answers

Probably the native for loop (well, everywhere except opera, where foreach is faster but that's another story).

However it really doesn't matter in 99.9% of cases.

Always prefer readable code over faster code when you can. All of these types of loops can handle hundreds of thousands of iterations every second on an average machine.

Readable code is much more important here - if a $.each over 100 elements seems more readable to you - by all means do that (I personally usually prefer Array.forEach, mainly because it's native and consistent with native .map .filter .reduce and so on). If you're performing a lot of work in the loop the difference becomes even smaller.

Lets say you have a method called doSomethingWithCurrent:

for(var i=0;i<elements.length;i++){
   var current = elements[i];
   doSomethingWithCurrent(current);
}

Vs:

elements.forEach(doSomethingWithCurrent);

The second is probably slower, but it's also a lot more readable (at least to me) which makes it more maintainable.

What about the following scenario - you have an array of objects with first and last names and you want to create a new array of strings containing the full name:

Plain loop:

var new = [];
for(var i=0;i<names.length;i++){
    new.push(names[i].firstName+" "+names[i].lastName);
}

Using map:

var new = names.map(function(elem){ 
    return elem.firstName+" "+elem.lastName;
});

Again, I find the second more readable, even if it's slower. Writing maintainable and readable code is often more important than writing fast code.

That said, "what's more readable" is often a matter of personal taste, it's important to stay consistent.

For desert - have some Knuth:

Programmers waste enormous amounts of time thinking about, or worrying about, the speed of noncritical parts of their programs, and these attempts at efficiency actually have a strong negative impact when debugging and maintenance are considered. We should forget about small efficiencies, say about 97% of the time: premature optimization is the root of all evil. Yet we should not pass up our opportunities in that critical 3%.

like image 131
Benjamin Gruenbaum Avatar answered Sep 18 '22 23:09

Benjamin Gruenbaum


When comparing Jquery loops to javascript loops you need to remember Jquery is implemented using javascript.

All Jquery functions eventually end up running standard javascript code.

As such this means that in most cases native javascript will be more efficient.

My prefered loop for speed is:

for(var i, ilen = MAXLENGTH; i < ilen; i++){
}

That is unless iterating through a javascript object in which case:

for(var key in object){
     if(object.hasOwnProperty(key)){

     }
}

This stands for the majority of use cases when comparing Jquery to javascript.

$('#elementid'); 

is much slower than

$(document.getElementById('elementId'));

along with a multitude of other examples.

Jquery can be used to make code look cleaner or for cross browser compatibility pre-version 2.

However in high performance situations if you can guarantee you only need to support modern browsers javascript is generally much quicker.

like image 39
Adam Avatar answered Sep 20 '22 23:09

Adam