[ACCEPTED]-Should I use jQuery.each()?-each

Accepted answer
Score: 30

This article (#3) ran some performance tests and found 3 that the jQuery .each function was about 2 10x as slow as the native javascript for 1 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.

Score: 15

The source code for jQuery's each is as 8 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 7 you can trace and see, in most cases it 6 is using a basic for loop where the only 5 overhead is really just the callback itself. Shouldn't 4 make a difference in performance.

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

Score: 8

This method should give you a dramatic speed 2 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 1 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";
    }
}
Score: 7

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

Example of what NOT to 1 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
});
Score: 6

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

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

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

More Related questions