Jquery each versus native for

var arr=[]; var k; for(var i=0;i<5000;i++) arr[i]=i; console.time("native loop"); var len=arr.length; for(var j=0;j<len;j++) k=arr[j]; console.timeEnd("native loop"); console.time("jq loop"); $(arr).each(function(i,el){ k=el; }); console.timeEnd("jq loop"); 

It generates 14 ms for its own loop and 3 ms for each jQuery.

I am using jQuery 1.6.2. If jquery uses its own loop behind the scenes, then how is this possible?

+7
source share
3 answers

I would think that this is related to the scope of your index variable - your j variable is global, which refers to the slowest case of accessing a variable. Each time your loop should reference j, it needs to check all the way to the chain of regions, return to the global object, and then get the value of the variable from here.

I get similar numbers in my console (Chrome, OS X - 13-15ms for for loop, 3-4ms for jQuery).

But if I do this:

 (function() { console.time("native loop with function scope"); var len=arr.length; for(var j=0;j++<len;) k=arr[j]; console.timeEnd("native loop with function scope");})() 

It runs in just 5 ms.

The difference in this case is that j is a local variable function, available immediately, first of all, the JavaScript engine searches for variables. len also local; the only global values ​​in this case are k and arr .

To get even more speed from this, make k the variable of the function region and go to arr as a parameter:

 (function(arr) { console.time("native loop 2"); var len=arr.length, k; for(var j=0;j++<len;) k=arr[j]; console.timeEnd("native loop 2");})(arr) > native loop 2: 0ms 

Okay, this is too fast. Perhaps arr should be larger:

 var arr=[]; for(var i=0;i<50000;i++) arr[i]=i; [Try again...] > native loop 2: 1ms 

This slowed down a bit.

With a 500k array, this code runs for 4ms in the JavaScript console on my machine. At 5M, this takes 36 ms.

You should also notice that you are not using the raw jQuery.each () call - you first wrap your array in $ (), create a jQuery object, and then call .each. A fairer test might be the launch

 $.each(arr, function(i,el){ k=el; }); 

This should be very close to the time of the second example above. jQuery adds a bit of overhead; checking the types of its arguments, but after that it starts a rather tight loop.

+8
source

http://www.georgepaterson.com/2011/08/30/javascript-performance-jquery-each-and-each-versus-alternatives/ jQuery.each designed to iterate through arrays and array objects like objects.
The opposite result of your Question.see link
http://jsfiddle.net/martinaglv/NcRsV/

0
source

All Articles