Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
142 views
Welcome To Ask or Share your Answers For Others

1 Answer

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...