Should I use jQuery.each()?

22,459

Solution 1

The source code for jQuery's each is as follows (Thank you John Resig and MIT License):

each: function( object, callback, args ) {
    var name, i = 0, length = object.length;

    if ( args ) {
        if ( length === undefined ) {
            for ( name in object )
                if ( callback.apply( object[ name ], args ) === false )
                    break;
        } else
            for ( ; i < length; )
                if ( callback.apply( object[ i++ ], args ) === false )
                    break;

    // A special, fast, case for the most common use of each
    } else {
        if ( length === undefined ) {
            for ( name in object )
                if ( callback.call( object[ name ], name, object[ name ] ) === false )
                    break;
        } else
            for ( var value = object[0];
                i < length && callback.call( value, i, value ) !== false; value = object[++i] ){}
    }

    return object;
}

As you can trace and see, in most cases it is using a basic for loop where the only overhead is really just the callback itself. Shouldn't make a difference in performance.

EDIT: This is with the realization that selector overhead has already occurred and you are given a populated array object.

Solution 2

This article (#3) ran some performance tests and found that the jQuery .each function was about 10x as slow as the native javascript for loop.

From 10 Ways to Instantly Increase Your jQuery Performance - 3. Use For Instead of Each
Using Firebug, it's possible to measure the time each of the two functions takes to run.

var array = new Array ();
for (var i=0; i<10000; i++) {
    array[i] = 0;
}

console.time('native');
var l = array.length;
for (var i=0;i<l; i++) {
    array[i] = i;
}
console.timeEnd('native');

console.time('jquery');
$.each (array, function (i) {
    array[i] = i;
});
console.timeEnd('jquery');

The above results are 2ms for native code, and 26ms for jQuery's "each" method. Provided I tested it on my local machine and they're not actually doing anything (just a mere array filling operation), jQuery's each function takes over 10 times as long as JS native "for" loop. This will certainly increase when dealing with more complicated stuff, like setting CSS attributes or other DOM manipulation operations.

Solution 3

This method should give you a dramatic speed improvement.

var elements = $('.myLinks').get(), element = null;
for (var i = 0, length = elements.length; i < length; i++) {
    element = elements[i];
    element.title = "My New Title!";
    element.style.color = "red";
}

Caching will also improve performance.

function MyLinkCache() {
    var internalCache = $('.myLinks').get();

    this.getCache = function() {
        return internalCache;  
    }

    this.rebuild = function() {
        internalCache = $('.myLinks').get();
    }
}

In use:

var myLinks = new MyLinkCache();

function addMyLink() {
    // Add a new link.
    myLinks.rebuild();
}

function processMyLinks() {
    var elements = myLinks.getCache(), element = null;
    for (var i = 0, length = elements.length; i < length; i++) {
        element = elements[i];
        element.title = "My New Title!";
        element.style.color = "red";
    }
}

Solution 4

One way to make sure you are getting the most out of jquery is to store the returned array of results in a variable rather than re-traversing the DOM everytime you need to get something.

Example of what NOT to do:

$('.myLinks').each(function(){
    // your code here
});
$('.myLinks').each(function(){
    // some more code here
});

Better practice:

var myLinks = $('.myLinks');
myLinks.each(function(){
    // your code here
});
myLinks.each(function(){
    // some more code here
});

Solution 5

Using native functionality will generally be faster than an abstraction, such as JQuery.each() method. However, the JQuery.each() method is easier to use and requires less coding on your part.

Truthfully, neither one is the right or wrong choice without any context. I'm of the oppinion that we should be writing easier code first, assuming it's good/legilble/clean code. If you come into a situation, such as the one you're describing, where there's a noticeable lag, than it's time to find out where your bottlenecks are and write faster code.

Replacing the JQuery.each() method in these scenarios might help, however, having not seen your code, it's possible you have bottlenecks unrelated to the JQuery method.

Share:
22,459
pr1001
Author by

pr1001

Updated on October 04, 2020

Comments

  • pr1001
    pr1001 over 3 years

    I'm doing very frequent iterations over arrays of objects and have been using jQuery.each(). However, I'm having speed and memory issues and one of the most called methods according to my profiler is jQuery.each(). What's the word on the street about its performance? Should I switch to a simple for loop? Of course I'm fixing the many issues in my own code too.

  • ChaosPandion
    ChaosPandion over 14 years
    Even better practice: do everything in one loop.
  • Justin Swartsel
    Justin Swartsel over 14 years
    Of course. And like most of us regretfully so. But what is your point specifically? My point is that the heart of "each" is just a for loop. I left the overhead you get from instantiating a jQuery object and selecting dom elements alone.
  • ChaosPandion
    ChaosPandion over 14 years
    What I am saying is don't underestimate the overhead of function calls.
  • Jason Orendorff
    Jason Orendorff over 14 years
    At the moment, function calls are in fact quite slow in JS. Working on it.
  • Justin Swartsel
    Justin Swartsel over 14 years
    Point well taken. Thanks guys.
  • Admin
    Admin over 11 years
    this should be answer. my dynamic paginations were choppy only because of each. also, link provides great advice. just noticed i'm only doing about 40%
  • Bradford
    Bradford about 11 years
    I was surprised by how slow these callbacks are: jsperf.com/jquery-each-vs-for-loop/31
  • Taryn
    Taryn over 9 years
    While this answer is over a year old and the link is helpful it would be better if you post the essential parts of the answer here, on this site, or your post risks being deleted See the FAQ where it mentions answers that are 'barely more than a link'. You may still include the link if you wish, but only as a 'reference'. The answer should stand on its own without needing the link.
  • Jace Rhea
    Jace Rhea over 9 years
    @bluefeet This answer is almost 5 years old. Give me a break. Also I did include the essential part of the link. "found that the jQuery .each function was about 10x as slow as the native javascript for loop." It doesn't get much more essential than that.
  • Taryn
    Taryn over 9 years
    @JaceRhea The only reason that I commented is that this was flagged as low quality and was requested that it be deleted. I figured I'd give you a chance to improve the "link-only" nature of it first.
  • Daniel Dewhurst
    Daniel Dewhurst over 7 years
    Surely both examples are the same if ran once? Before jQuery iterates through the object, it sets up a variable, just as you do in your second example. If you had to run through the .each statement multiple times, then maybe caching the variable would help.