Speed Question jQuery.each vs. for loop

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-vs-for-speed-js-perf

jQuery.each

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

For Loop with Caching

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

For Loop without Caching

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

Pre-calculated Length attempt

precalculated-length

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

Free book: Jump Start HTML5 Basics

Grab a free copy of one our latest ebooks! Packed with hints and tips on HTML5's most powerful new features.

  • http://danmathisen.com/ 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]; };

    • http://jquery4u.com/ jQuery4u

      Much faster results mate, I’ve added it to the post. http://jsperf.com/jquery-each-vs-for-loop/214

      • http://danmathisen.com/ dmathisen

        Awesome. I wasn’t expecting that great an improvement. Thanks for trying it out.

  • Ray

    and how about using browser native array’s forEach ?

    • http://jquery4u.com/ jQuery4u

      It’s slower – see jsperf

  • FTM

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

  • http://www.facebook.com/vladimir.kharlampidi Vladimir Kharlampidi

    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.