Showing posts with label Performance. Show all posts
Showing posts with label Performance. Show all posts

Javascript for() loop vs jQuery .each() performance comparison

This post is an outcome of 15 minutes of free time and a question that I had yesterday. This question were:

How fast jQuery’s .each() method is?
How does it compare to javascript’s native for loop?
It is clear without any performance tests that native javascript for loop is faster, but I always used jQuery’s .each() utility with caution. It always felt like I will get a performance penalty for using it. So I tried to never use it.

So today, I wrote up a little javascript performance test and got my answers. Basically, I created an array and iterated through it using native for loop and jQuery’s .each() iterator. All I did was just an iteration and no array amendments or any other logic. I know it is very basic, but that’s exactly what I want to know. How fast they iterate!

Performance test code:

console.time('TestNative');
for( i=0; i < myArray.length; i++){
myArray[i];
}
console.timeEnd('TestNative');

console.time('TestjQuery');
jQuery.each(myArray, function(i, val) {
val;
});
console.timeEnd('TestjQuery');

Performance test results:

JavaScript Native FOR loop

Array size Time
========== ======

10,000 7ms
100,000 62ms
1,000,000 613ms


jQuery .each() loop

Array size Time
========== ======

10,000 10ms
100,000 177ms
1,000,000 1100ms

Usually we don’t have more than 1000 items in our arrays and objects, that is why I guess it can be concluded that using .each() loop in our code will not cause any performance penalties.