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.