By Sam Deering

Speed Question jQuery.each vs. for loop

By Sam Deering

Quick point. It might be beneficial to mention that we are using vanilla for loops instead of jQuery.each for speed (up to 84% faster). Using a for loop with variable caching produces even faster results jsperf – each vs for.



$.each(a, function() {
  e = this;

For Loop with Caching

for ( var i = 0, len = a.length; i For Loop without Caching

for (var i = 0; i Pre-calculated Length attempt


var len = a.length, i = 0;
for (i; i

  • Dan

    I’d like to see these results without calculating length at every iteration.

    var len = a.length, i = 0;
    for (i; i < len; i++) { e = a[i]; };

  • Ray

    and how about using browser native array’s forEach ?

  • FTM

    Preety much same as PHPs for and foreach loop.
    Good reading.

  • This is an expected behavior, every native function will be faster than with jQuery wrapper. But disadvantage and advantage of jQuery .each is that it calls anonymous function. Of course it is not good for perfomance, but it is good from the point of view that code which executed is inside of its own scope. Sometimes it is very useful.

Get the latest in JavaScript, once a week, for free.