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 < len; i++) { e = a[ i] ; }; [/js]

For Loop without Caching

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

Pre-calculated Length attempt


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

  • 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]; };

    • jQuery4u

      Much faster results mate, I’ve added it to the post.

      • 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 ?

    • jQuery4u

      It’s slower – see jsperf

  • FTM

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

  • 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.



Learn Coding Online
Learn Web Development

Start learning web development and design for free with SitePoint Premium!

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